Sub topic 17
When useReducer fits better
This chapter assumes you can write function components, use useState with objects and arrays, and know why state updates must not mutate. It also assumes you are comfortable with updater functions such as setCount(c => c + 1).
useState is enough for most components. Sometimes a component collects many handlers that all change the same piece of state in different ways. The update logic ends up scattered across the component, and it is hard to see every way the state can change. useReducer moves that logic into one function.
What useReducer is
A reducer is a pure function that takes the current state and an action, and returns the next state. An action is a plain object that describes what happened, usually with a type field.
useReducer(reducer, initialState) returns the current state and a dispatch function. Calling dispatch(action) asks React to run your reducer with the latest state and that action. React then re-renders with the value the reducer returns.
The render cycle is the same as with useState. Each render still sees a snapshot, and the new state appears on the next render. The change is where the update logic lives.
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
case 'reset':
return { count: 0 };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</>
);
}The handlers no longer say how to compute the next state. They only say what happened.
A realistic case: a todo list
The todo list from the array chapter had add, toggle, and remove functions that each called setTodos with different logic. With a reducer, every transition sits in one place.
import { useReducer, useState } from 'react';
let nextId = 1;
function todosReducer(todos, action) {
switch (action.type) {
case 'added':
return [...todos, { id: action.id, text: action.text, done: false }];
case 'toggled':
return todos.map(t =>
t.id === action.id ? { ...t, done: !t.done } : t
);
case 'removed':
return todos.filter(t => t.id !== action.id);
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
function TodoList() {
const [todos, dispatch] = useReducer(todosReducer, []);
const [text, setText] = useState('');
function add() {
dispatch({ type: 'added', id: nextId++, text });
setText('');
}
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<button onClick={add}>Add</button>
<ul>
{todos.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: 'removed', id: t.id })}>
Delete
</button>
</li>
))}
</ul>
</>
);
}Two details are worth noting.
- The text field still uses
useState. It holds a transient input value, not part of the todo list's transitions. Mixing both hooks in one component is normal. - The
idis generated in the handler, not in the reducer. The reducer must be pure, so it cannot increment a counter or callMath.random(). Pass such values in through the action.
Reducer rules
React may call your reducer more than once with the same inputs, for example in development Strict Mode, to help you find impurities. A reducer should therefore follow the same rules as any render logic.
- Compute the result only from
stateandaction. - Do not mutate
stateoraction. Return a new object or array. - Do not perform side effects such as network requests, timers, or writing to storage.
- Always return a state value. A
casethat forgets toreturnproducesundefined, which breaks the next render.
If the reducer returns the same state it received, React sees no change and skips re-rendering the children and running effects.
Comparing useState and useReducer
| Concern | useState | useReducer |
|---|---|---|
| Code size for simple state | Smaller | More boilerplate |
| Many handlers changing related state | Logic spread across handlers | Logic gathered in one function |
| Next state depends on several fields | Possible, but handlers get long | Natural fit |
| Testing update logic | Test through the component | Test the reducer as a plain function |
| Debugging | Log inside each handler | Log every action in one place |
| Passing updates to children | Pass several setters or callbacks | Pass one `dispatch` |
The reducer is a plain function, so you can test it without rendering anything.
function counterReducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
}
console.assert(
counterReducer({ count: 1 }, { type: 'increment' }).count === 2,
'increment should add one'
);Reducers and the snapshot rule
Dispatching follows the same snapshot behavior you learned for setters. Inside one handler, state is fixed for that render, and dispatching does not change it immediately.
import { useReducer } from 'react';
function reducer(state, action) {
if (action.type === 'increment') {
return { count: state.count + 1 };
}
return state;
}
function Triple() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
function addThree() {
dispatch({ type: 'increment' });
dispatch({ type: 'increment' });
dispatch({ type: 'increment' });
console.log(state.count); // still the old value in this handler
}
return <button onClick={addThree}>{state.count}</button>;
}Clicking once adds three, not one. Each queued action runs through the reducer in order, and each call receives the result of the previous one. This is the same guarantee that updater functions give useState. The console.log still prints the old count, because the new state is available only on the next render.
Deciding when to switch
Switch when you see these signs.
- Several event handlers update the same state, and you have to read all of them to know what states are possible.
- The next state depends on a combination of fields, such as a form with a status, an error, and data that must change together.
- You want to write tests for the transitions without rendering.
- A child needs to trigger many kinds of updates, and you are passing down several callbacks.
Stay with useState when the state is a single value, a toggle, or a field with no coupling to other fields. Converting a trivial counter to a reducer adds code without making anything clearer.
There is no need to decide early. Moving from useState to useReducer later is a mechanical refactor. Collect the state into one object, write a case for each handler, and replace each setter call with a dispatch.
Common mistakes
- Mutating state in the reducer. Writing
state.count++and returningstatemakes React see the same object, so the UI may not update. Return a new object. - Missing default case. Without a
defaultthat throws or returnsstate, a mistyped action type silently producesundefinedor does nothing. Throwing makes the typo visible. - Side effects in the reducer. Fetching data or generating ids inside the reducer breaks purity and behaves oddly under Strict Mode. Do this in the handler and pass the result in the action.
- Putting derived values in state. The rule from earlier chapters still applies. Compute totals and filtered lists during render rather than storing them in the reducer state.
- Modeling actions as setters. Actions such as
{ type: 'set_count', value: 5 }bring back the scattered logic you were trying to avoid. Name actions after what happened, such asaddedortoggled.
Exercise
A component keeps { status, error, data } in useState. Three handlers each call setState with a different combination of those fields, and sometimes status is 'success' while error is still set. How would useReducer help, and why should the fetch call itself stay out of the reducer?
Show answer
Define actions such as 'fetchstarted', 'fetchsucceeded', and 'fetch_failed'. The reducer returns a complete, consistent object for each action, for example setting error to null on success, so the fields cannot drift apart. The fetch call is a side effect, and a reducer must be pure because React may call it more than once with the same inputs. Start the request in the handler or an effect and dispatch the outcome as an action.
Exercise
In a reducer, you write case 'increment': state.count += 1; return state;. The button is clicked and nothing changes on screen. Why, and what is the fix?
Show answer
The reducer mutates the existing state object and returns the same reference, so React compares the old and new state, sees no change, and skips the re-render. Return a new object instead: return { ...state, count: state.count + 1 };.