Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.6 — Scaling Up with a Reducer and Context
React · Example 1 of 3

A task store: reducer + two contexts + custom hooks

After the tick, only the two components that read the tasks render again. AddTask reads only dispatch, which never changes, and it isn't re-rendered by its parent either: App created it, and App didn't render. Type in the box: only AddTask renders, because the text is its own local state.

Combine a reducer (all the update logic) with context (reach anywhere): a provider component owns useReducer and puts state and dispatch in two separate contexts, and small custom hooks such as useTasks() and useTasksDispatch() let any component read or update the store without props.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Build a NotificationsProvider with a reducer (added, dismissed), two contexts and two hooks, useNotifications() and useNotify() (which returns a notify(text) function).

02

Write a useTaskActions() hook for the task store that returns { addTask, toggleTask, deleteTask }, and explain why it uses useMemo.

Explain it without notes

01

Why do you combine useReducer with context? What does each part contribute?

02

Why use two contexts, one for state and one for dispatch?

03

What is the point of custom hooks like useTasks() instead of calling useContext directly?

04

What are the limits of reducer + context, and what would you use beyond them?

A task store: reducer + two contexts + custom hooks

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

AddTask rendered
TaskList rendered: 2 tasks
Summary rendered
--- tick the second task
TaskList rendered: 2 tasks
Summary rendered
0 left