Sub topic 11
Passing state and dispatch through context
This chapter assumes you can write a reducer, call useReducer, and use useContext at a basic level. It also assumes you know that dispatch keeps the same identity between renders.
The prop-drilling problem
useReducer returns state and dispatch to one component. If a button ten levels down needs to dispatch an action, you would have to pass dispatch through every component in between. Context removes that chain. A provider component calls useReducer once, and any descendant can read what it needs.
Two contexts, not one
Put state and dispatch in separate contexts. dispatch never changes identity, so the dispatch context value never changes. A component that only dispatches then does not re-render when the state changes.
Building the provider
The provider calls useReducer and wraps its children in both contexts. Custom hooks hide the useContext calls and fail loudly when used outside the provider.
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() {
const value = useContext(CountContext);
if (value === null) {
throw Error('useCount must be used inside CountProvider');
}
return value;
}
export function useCountDispatch() {
const dispatch = useContext(CountDispatchContext);
if (dispatch === null) {
throw Error('useCountDispatch must be used inside CountProvider');
}
return dispatch;
}The state here is a number, and 0 is not null, so the guard in useCount is safe. If your state can legitimately be null, use a unique default such as undefined and check for that instead.
Using it in components
Wrap the part of the tree that needs the state, then read it with the hooks. Save the provider above as CountContext.jsx.
import { CountProvider, useCount, useCountDispatch } from './CountContext';
function CountDisplay() {
const count = useCount();
return <p>Count: {count}</p>;
}
function IncrementButton() {
const dispatch = useCountDispatch();
return (
<button onClick={() => dispatch({ type: 'incremented' })}>+1</button>
);
}
export default function App() {
return (
<CountProvider>
<CountDisplay />
<IncrementButton />
</CountProvider>
);
}Neither child receives props. IncrementButton reads only the dispatch context, so a context update caused by a state change does not re-render it.
Why `children` matters
CountProvider renders {children} that were created by its parent. When the reducer updates the state, the provider re-renders, but the children elements are the same objects as before. React skips them unless they consume a changed context. If you built the child tree inside the provider instead, every child would re-render on each state change.
Common errors
- One context holding
{ state, dispatch }. Creating a new object on each render makes every consumer re-render, including those that only dispatch. - Using a hook outside its provider. Without a guard, you get
nulland a confusing error later, such as reading a property ofnull. The guard turns it into a clear message. - Putting everything in one global provider. Every consumer of a context re-renders when its value changes. Place providers as low in the tree as the consumers allow.
Exercise
Exercise
A TodoProvider passes { todos, dispatch } as a single object in one context. Components that only render an "Add" button re-render whenever a todo is toggled. Why does this happen, and how do you fix it?
Show answer
The provider creates a new { todos, dispatch } object on each render, so every consumer of that context sees a changed value and re-renders. Split it into a TodosContext holding todos and a TodosDispatchContext holding dispatch. Because dispatch has a stable identity, components that only call useContext(TodosDispatchContext) no longer re-render on state changes.