Sub topic 11
Scaling up with useReducer and context
What this chapter assumes
You should know createContext, Provider and useContext. You should also know how to put useState inside a provider component and why a new object passed as value re-renders every consumer. This chapter adds useReducer to that setup. If you haven't used useReducer, the short version is that it takes a function (state, action) => newState and an initial state. It returns the current state and a dispatch function that sends actions to that function.
Why useState in a provider stops scaling
A provider that holds one or two useState values is easy to read. As the shared state grows, three problems appear:
- Scattered logic. Every consumer that changes the state needs a setter, or a wrapper function around a setter. The rules for valid changes end up spread across components.
- A growing context value. Each new operation adds another function to the object you pass down. That object then has to be memoized and kept stable.
- Hard-to-follow updates. Several components calling different setters on related data make it hard to see which change caused which result.
useReducer puts every state transition in one function. Components stop calling setters. They describe what happened, such as "task 3 was toggled", and the reducer decides the new state.
The pattern: one reducer, two contexts
The standard shape is a provider that owns a reducer and publishes two things through two separate contexts: the current state, and the dispatch function.
import { createContext, useContext, useReducer } from 'react';
const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);
function tasksReducer(tasks, action) {
switch (action.type) {
case 'added':
return [...tasks, { id: action.id, text: action.text, done: false }];
case 'toggled':
return tasks.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
default:
throw new Error('Unknown action: ' + action.type);
}
}
export function TasksProvider({ children }) {
const [tasks, dispatch] = useReducer(tasksReducer, []);
return (
<TasksContext.Provider value={tasks}>
<TasksDispatchContext.Provider value={dispatch}>
{children}
</TasksDispatchContext.Provider>
</TasksContext.Provider>
);
}
export function useTasks() {
return useContext(TasksContext);
}
export function useTasksDispatch() {
return useContext(TasksDispatchContext);
}Put this in a file such as TasksContext.jsx. Only the provider and the two hooks are exported, so components never touch the context objects directly.
Why the two contexts are separate
React guarantees that the dispatch function returned by useReducer keeps the same identity for the life of the component. The tasks array gets a new identity after every action that changes it.
If both lived in one context object, { tasks, dispatch }, every dispatch would create a new object and re-render every consumer, including components that only send actions. With two contexts, a component that calls only useTasksDispatch() never re-renders because of a task change. Because dispatch is stable, you also don't need useMemo or useCallback for it.
Using it in components
The consumers below use the hooks. AddTask only dispatches. TaskList reads the state and also dispatches.
import { useState } from 'react';
import { TasksProvider, useTasks, useTasksDispatch } from './TasksContext';
let nextId = 0;
function AddTask() {
const [text, setText] = useState('');
const dispatch = useTasksDispatch();
function handleAdd() {
if (text.trim() === '') return;
dispatch({ type: 'added', id: nextId++, text });
setText('');
}
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={handleAdd}>Add</button>
</div>
);
}
function TaskList() {
const tasks = useTasks();
const dispatch = useTasksDispatch();
return (
<ul>
{tasks.map((t) => (
<li key={t.id}>
<label>
<input
type="checkbox"
checked={t.done}
onChange={() => dispatch({ type: 'toggled', id: t.id })}
/>
{t.text}
</label>
</li>
))}
</ul>
);
}
export default function App() {
return (
<TasksProvider>
<AddTask />
<TaskList />
</TasksProvider>
);
}Two details easy to miss.
First, nextId lives outside the reducer and is passed in the action. A reducer must be a pure function. Given the same state and action, it must return the same result. If it generated ids or read the clock, that rule would break.
Second, when the reducer runs and TasksProvider re-renders, AddTask and TaskList are not re-rendered because their parent re-rendered. children is a prop created by App, and its element identity does not change. React skips re-rendering them unless a context they read has changed. This is why only TaskList updates when a task is added. AddTask re-renders only because of its own text state.
How an update flows
Rules the reducer must follow
- Return new objects. Copy with spread,
maporfilter. If you mutatetasksand return it, React sees the same reference and may skip the update. - Stay pure. No fetch calls, timers or random numbers inside the reducer. Do that work in event handlers or effects, then dispatch the result.
- Throw on unknown actions. The
defaultbranch above makes a misspelled action type fail loudly. Silently returning the old state hides the bug. - Expect double calls in development. In Strict Mode, React calls reducers twice to catch impurity. An impure reducer shows up as duplicated entries.
Growing the actions
Adding behavior means adding a case, and no component needs to change shape. A deletion looks like this:
case 'deleted':
return tasks.filter((t) => t.id !== action.id);Action objects can carry whatever the reducer needs, but keep them small and descriptive. Name actions after what happened ('toggled') instead of the code to run ('setDoneFlag'). The reducer then holds the meaning of each event, and components stay simple.
If the initial state is expensive to compute, pass a third argument: useReducer(tasksReducer, initialArg, init). React calls init(initialArg) once. This is useful when restoring state from localStorage.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Putting `{ state, dispatch }` in one context | Dispatch-only components re-render on every change | Use two contexts |
| Mutating state in the reducer | UI does not update, or updates inconsistently | Return a new array or object |
| Generating ids inside the reducer | Different ids in Strict Mode, hard-to-test reducer | Create the id in the caller and put it in the action |
| Using the hooks outside the provider | `null` returned, then `Cannot read properties of null` | Wrap the tree in the provider, or throw a clear error in the hook |
| One giant reducer for unrelated data | Every consumer re-renders for unrelated updates | Split into separate providers by concern |
The last row connects to the next chapter. A reducer context still re-renders every consumer of the state context whenever any part of the state changes. If different components read different slices, splitting contexts limits that cost.
Exercise
Add a 'deleted' action to tasksReducer and a Delete button to each item in TaskList. Does AddTask re-render when a task is deleted? Explain why or why not.
Show answer
Add case 'deleted': return tasks.filter((t) => t.id !== action.id); to the reducer. In TaskList, add <button onClick={() => dispatch({ type: 'deleted', id: t.id })}>Delete</button> inside each <li>. AddTask does not re-render because of the deletion. It reads only TasksDispatchContext, whose value (dispatch) keeps the same identity. Its parent TasksProvider re-renders, but AddTask is passed through children, so its element is unchanged and React skips it.