Manage complex state with useReducer
Move state updates for a React component into a reducer function with useReducer, so every transition is named and lives in one place.
When several handlers each call a different setter and the pieces must change together, the logic scatters across the component. A reducer gathers every transition into one function.
import { useReducer } from 'react';
function reducer(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}`);
}
}
export function Todos() {
const [todos, dispatch] = useReducer(reducer, []);
return (
<div>
<button onClick={() => dispatch({ type: 'added', id: 1, text: 'Write snippet' })}>
Add
</button>
<ul>
{todos.map((t) => (
<li key={t.id} onClick={() => dispatch({ type: 'toggled', id: t.id })}>
{t.done ? '✓ ' : ''}{t.text}
</li>
))}
</ul>
</div>
);
}(click Add) -> Write snippet
(click the item) -> ✓ Write snippetdispatch sends an action, React calls reducer(currentState, action) and renders with what it returns. The reducer must be pure and must return a new array rather than mutate, which is what the spread and map do. See useReducer.
For one or two independent values useState is shorter. Reach for a reducer when updates depend on several fields or when you want the transitions to be easy to test.