Sub topic 11
Passing state and dispatch through context
This chapter assumes you can write a reducer, call useReducer, and dispatch action objects. It also assumes you know what createContext and useContext do in basic form. It covers sharing a reducer's state and dispatch function with a whole component subtree, without passing props through every level.
The problem: prop drilling
useReducer returns [state, dispatch] inside one component. Suppose a deeply nested button needs to dispatch an action, or a distant list needs to read the state. Without context, every component between them has to accept and forward state and dispatch as props. This is called prop drilling. The intermediate components don't use these props. They only pass them along.
Context removes that forwarding. A component near the top owns the reducer and publishes its results. Any descendant can read them directly.
The two-context pattern
You could put { state, dispatch } in one context. The usual pattern uses two contexts instead: one for the state and one for dispatch.
import { createContext, useContext, useReducer } from 'react';
const CountContext = createContext(null);
const CountDispatchContext = createContext(null);
function countReducer(state, action) {
switch (action.type) {
case 'incremented':
return state + 1;
default:
throw Error('Unknown action: ' + action.type);
}
}
export function CountProvider({ children }) {
const [count, dispatch] = useReducer(countReducer, 0);
return (
<CountContext.Provider value={count}>
<CountDispatchContext.Provider value={dispatch}>
{children}
</CountDispatchContext.Provider>
</CountContext.Provider>
);
}
export function useCount() {
return useContext(CountContext);
}
export function useCountDispatch() {
return useContext(CountDispatchContext);
}The code has three parts:
- Two context objects, created once at module level.
- A provider component that calls
useReducerand wraps itschildrenin both context providers. - Two small custom hooks, so consumers never touch the context objects directly.
Components import useCount or useCountDispatch. They don't need to know that contexts are involved.
A fuller example: a task list
Here is the same idea with a realistic reducer. All the context code lives in one file, so the contexts and the reducer stay together.
// TasksContext.jsx
import { createContext, useContext, useReducer } from 'react';
const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);
const initialTasks = [
{ id: 0, text: 'Read about context', done: true },
{ id: 1, text: 'Write a provider', done: false },
];
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
);
case 'deleted':
return tasks.filter(t => t.id !== action.id);
default:
throw Error('Unknown action: ' + action.type);
}
}
export function TasksProvider({ children }) {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
return (
<TasksContext.Provider value={tasks}>
<TasksDispatchContext.Provider value={dispatch}>
{children}
</TasksDispatchContext.Provider>
</TasksContext.Provider>
);
}
export function useTasks() {
const tasks = useContext(TasksContext);
if (tasks === null) {
throw Error('useTasks must be used inside a <TasksProvider>');
}
return tasks;
}
export function useTasksDispatch() {
const dispatch = useContext(TasksDispatchContext);
if (dispatch === null) {
throw Error('useTasksDispatch must be used inside a <TasksProvider>');
}
return dispatch;
}The two hooks check for null. The contexts are created with null as the default value. A component rendered outside the provider would otherwise get null and fail later, far from the real mistake. The check turns that into an immediate, readable error. The null test is safe for tasks because the reducer's state is always an array, never null.
Now the consumers. None of them receive tasks or dispatch as props.
// AddTask.jsx
import { useState } from 'react';
import { useTasksDispatch } from './TasksContext';
let nextId = 2;
export default 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>
</>
);
}// TaskList.jsx
import { useTasks, useTasksDispatch } from './TasksContext';
export default 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>
<button onClick={() => dispatch({ type: 'deleted', id: t.id })}>
Delete
</button>
</li>
))}
</ul>
);
}// App.jsx
import { TasksProvider } from './TasksContext';
import AddTask from './AddTask';
import TaskList from './TaskList';
export default function App() {
return (
<TasksProvider>
<h1>Tasks</h1>
<AddTask />
<TaskList />
</TasksProvider>
);
}AddTask only writes, so it uses only the dispatch hook. TaskList reads and writes, so it uses both. App does not mention state at all. It just places the provider.
Why two contexts instead of one
When a context value changes, React re-renders every component that calls useContext on that context. Compare the two designs.
| Design | Context value | What re-renders when state changes |
|---|---|---|
| One context holding `{ state, dispatch }` | An object | Every consumer, including components that only dispatch |
| Two contexts | State in one, `dispatch` in the other | Only components that read the state context |
React guarantees that dispatch keeps the same identity across renders. The dispatch context's value therefore never changes, and components that only call useTasksDispatch are never re-rendered because of it. In the task example, typing into AddTask and adding tasks changes the state context, but AddTask does not subscribe to it.
There is a second part to this. The provider re-renders when its reducer state changes. Its children prop holds elements that were created by the provider's parent (App), and those elements keep the same identity. React sees identical elements and skips re-rendering them unless they consume a changed context. If you instead wrote the children inline inside the provider component, they would be recreated on every provider render.
Gotchas
An object literal as the context value
If you do choose a single context, this version has a hidden cost:
const [state, dispatch] = useReducer(reducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);The { state, dispatch } literal is a new object on every render of the provider. React compares context values with Object.is, so consumers re-render each time, even if state did not change. This happens, for example, when the provider's parent re-renders. Memoize the value:
import { createContext, useMemo, useReducer } from 'react';
const AppContext = createContext(null);
export function AppProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
const value = useMemo(() => ({ state, dispatch }), [state]);
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
}The dependency list contains only state because dispatch is stable. With the two-context pattern you don't need useMemo at all, since each value is already a plain reference that changes only when it should.
Context does not bypass re-rendering costs
Every consumer of the state context re-renders on every state change, even if it only uses one field. If TaskList and a small TaskCount badge both read the whole tasks array, both re-render when a task is toggled. For most apps this is fine. If it becomes a measured problem, you can split the state into several reducers and providers, or move the expensive subtree behind memo and pass it only the values it uses.
Provider placement defines scope
Only components below a provider can read its context. A component rendered outside it gets the default value, null here. Put the provider as low in the tree as works, but above every component that needs it. Placing one provider above the whole app makes the state global. Placing one above a single page or feature keeps the state local, and it resets when that part of the tree unmounts.
You can also render the same provider more than once. Each instance runs its own useReducer, so each has independent state. Two TasksProviders on one page give you two separate task lists.
Reducer rules still apply
Putting the reducer behind context does not change the rules from earlier chapters. The reducer must be pure, return new objects and arrays instead of mutating, and handle every action type. Strict Mode still calls it twice in development to expose impurity.
When to use this pattern
Context with a reducer fits state that many components at different depths need, such as a task list, a shopping cart, or a form that spans several nested panels. It is a poor fit for state that only a parent and its direct child share. In that case, props are simpler and easier to trace.
Exercise
A component Toolbar shows three buttons that each call dispatch but never read state. The app uses a single context whose provider passes value={{ state, dispatch }} without useMemo. Every time a task is toggled, Toolbar re-renders. Name two changes that stop Toolbar from re-rendering because of state changes, and explain why each works.
Show answer
First, split the provider into two contexts, one holding state and one holding dispatch. dispatch has a stable identity, so the dispatch context's value never changes, and a component that subscribes only to it is not re-rendered when state changes. Second, keep one context but wrap the value in useMemo(() => ({ state, dispatch }), [state]). This stops unrelated provider re-renders from creating a new object. It does not help here, because state itself changed, so Toolbar still re-renders. Only the two-context split fixes this case. The useMemo change prevents extra re-renders when the provider re-renders without a state change.
Exercise
Why do the custom hooks useTasks and useTasksDispatch throw an error when the context value is null?
Show answer
The contexts are created with null as their default, which is what a component receives when it is rendered outside the provider. Without the check, the component would get null and fail later with an unrelated message such as "tasks.map is not a function". Throwing in the hook reports the real mistake, a missing <TasksProvider>, at the point where it happens.