Sub topic 11
Scaling up with useReducer and context
This chapter assumes you know createContext, Providers, useContext, and how to wrap a context in a provider component with a custom hook. It also assumes you know that a context change re-renders every consumer.
Why move to a reducer
useState works well while a context holds one value and a few setters. As the state grows, every component that changes it needs its own setter. Update logic spreads across the tree.
A reducer is a function (state, action) => newState. It collects all update logic in one place. Components describe what happened by dispatching an action, such as { type: 'added' }. They don't describe how the state changes. Combined with context, any component can dispatch an action without receiving callbacks through props.
The pattern
Create two contexts. One holds the state and the other holds dispatch. A single provider component creates both with useReducer.
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);
}The reducer must be pure. It never mutates tasks. It returns a new array or object each time, which is why the code uses spread and map. The default branch throws, so a mistyped action type fails loudly.
Using it in components
Wrap the part of the tree that needs tasks in <TasksProvider>. Then any descendant can read or update the list.
import { useState } from 'react';
import { useTasks, useTasksDispatch } from './TasksContext';
let nextId = 0;
export function AddTask() {
const [text, setText] = useState('');
const dispatch = useTasksDispatch();
return (
<>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button
onClick={() => {
dispatch({ type: 'added', id: nextId++, text });
setText('');
}}
>
Add
</button>
</>
);
}
export 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>
);
}AddTask only reads the dispatch context. React guarantees that dispatch keeps the same identity between renders. When the task list changes, the dispatch context value does not change, so AddTask is not re-rendered by the context. It still re-renders if its parent re-renders, as in any React component. Splitting the contexts therefore gives you some of the re-render control from the previous chapters at no extra cost.
How the data flows
Common errors
- Mutating state in the reducer. Calling
tasks.push(...)and returningtasksreturns the same reference. React sees no change and may skip the update. - Using a hook outside the provider. With a
nulldefault,useTasks()returnsnullandtasks.mapfails. Add the check from the custom-hook chapter if you want a clearer message. - Putting everything in one context. Combining state and dispatch in one object makes dispatch-only components re-render on every state change.
- Putting side effects in the reducer. Network calls and random values belong in event handlers or effects. React may call a reducer more than once in development to detect impurity.
Exercise
A component only calls dispatch to add tasks. When the task list changes, why does it not re-render because of context, given the two-context setup?
Show answer
It reads only TasksDispatchContext. The dispatch function keeps the same identity across renders, so that context's value does not change. Only consumers of TasksContext are notified when the task list changes.
Exercise
Add a 'deleted' action to tasksReducer that removes a task by id. Write the new case.
Show answer
case 'deleted': return tasks.filter((t) => t.id !== action.id);