React Context or useReducer? They solve different problems.
A reducer calculates the next state from the current state and an action. Context makes a provided value available to descendants.
Use useState for simple local updates. A reducer can organize richer transitions; add Context when passing values through the tree becomes inconvenient.
Understand it. Then fix it.
Transport and transition.
They solve different problems. A reducer calculates the next state from the current state and an action. Context makes a value available to descendants.
The reducer changes the count.
This reducer adds one for an add action. Dispatching that action changes zero to one. The reducer belongs to useReducer, not to Context.
function reducer(n, action) {
return action.type === "add"
? n + 1 : n;
}
const [n, dispatch] =
useReducer(reducer, 0);
const add = () =>
dispatch({ type: "add" });Context carries the result.
The provider passes the count down. A descendant reads it with useContext. Dispatch can travel through another context, or just through a button prop.
<CountContext value={n}>
<Counter />
</CountContext>
// Inside Counter:
const n = useContext(CountContext);Small update? useState is enough.
For a simple counter, useState is enough. A reducer helps organize richer transitions. Add Context only when passing values down becomes inconvenient.
const [n, setN] = useState(0);
const add = () => setN(n => n + 1);Code blocks are teaching excerpts. Keep the surrounding error handling and application requirements.
Save the code excerpts ↓Read the full transcript
Should I use Context or useReducer? My counter has two buttons and already wants an architecture diagram. They solve different problems. A reducer calculates the next state from the current state and an action. Context makes a value available to descendants. This reducer adds one for an add action. Dispatching that action changes zero to one. The reducer belongs to useReducer, not to Context. The provider passes the count down. A descendant reads it with useContext. Dispatch can travel through another context, or just through a button prop. For a simple counter, useState is enough. A reducer helps organize richer transitions. Add Context only when passing values down becomes inconvenient. The counter now has a transport department. Still cannot count past the budget.