Sub topic 17
When useReducer fits better
This chapter assumes you know useState, updater functions, and immutable updates to objects and arrays. It covers the point where several useState calls and handlers become hard to follow, and how useReducer helps.
The problem: scattered update logic
A component can grow handlers that each change state in a slightly different way. Fix a bug in one handler and you may need to repeat it in three others. A reducer moves all of the update logic into one function.
A reducer is a 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.
The same todo list with a reducer
import { useReducer, useState } from 'react';
let nextId = 1;
function todosReducer(todos, action) {
switch (action.type) {
case 'added':
return [...todos, { id: nextId++, text: action.text, done: false }];
case 'toggled':
return todos.map(t =>
t.id === action.id ? { ...t, done: !t.done } : t
);
case 'deleted':
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', 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: 'deleted', id: t.id })}>
Delete
</button>
</li>
))}
</ul>
</>
);
}useReducer returns the current state and a dispatch function. Calling dispatch queues an action. React then calls your reducer with the latest state and that action, and re-renders with the result. Handlers now say what happened, and the reducer decides how state changes.
When to choose it
| Situation | Better fit |
|---|---|
| One value, or a few independent values | `useState` |
| Many handlers change the same state in different ways | `useReducer` |
| The next state depends on a set of rules | `useReducer` |
| You want to test update logic without rendering | `useReducer` |
Rules for reducers
- A reducer must be pure. It computes the next state from its arguments only, with no network calls, timers, or mutation of
state. - Return a new object or array for each change, as you do with
useState. - Keep ids out of the reducer where possible. In the example above,
nextId++changes a module variable, which breaks purity. React may call reducers twice in development to expose this. In real code, create the id in the handler and pass it in the action.
Exercise
A component has five useState calls, and three event handlers each update four of them together. Which Hook should you consider, and what two things does it return?
Show answer
Consider useReducer. It returns the current state and a dispatch function. Handlers dispatch actions, and one reducer function applies all the update logic.