React / 84
useReducer: state changes as actions
Move every way your state can change into one pure function. Handlers dispatch plain action objects that say what happened, and the reducer returns the next state.
The shape
const [state, dispatch] = useReducer(reducer, initialState);reducer: a function(state, action) => nextState. It's the only place the state changes.dispatch: what you call from handlers, with an action, a plain object describing what happened:dispatch({ type: "deleted", id: 3 }).- React calls your reducer with the current state and the action, stores what it returns, and re-renders.
1 · event handler
The user ticks a todo
dispatch({ type: "toggled", id: 2 })2 · reducer (pure)
todosReducer(todos, action)
3 · re-render
React stores it and re-renders
Example: a todo list
export 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 "deleted":
return todos.filter((t) => t.id !== action.id);
default:
throw new Error(`Unknown action: ${action.type}`);
}
}import { useReducer } from "react";
import { todosReducer } from "./todosReducer";
let nextId = 3;
const initialTodos = [
{ id: 1, text: "Buy paneer", done: true },
{ id: 2, text: "Book a table", done: false },
];
export default function TodoApp() {
const [todos, dispatch] = useReducer(todosReducer, initialTodos);
return (
<>
<button onClick={() => dispatch({ type: "added", id: nextId++, text: "New todo" })}>Add</button>
<ul>
{todos.map((t) => (
<li key={t.id}>
<input type="checkbox" checked={t.done} onChange={() => dispatch({ type: "toggled", id: t.id })} />
{t.text}
<button onClick={() => dispatch({ type: "deleted", id: t.id })}>Delete</button>
</li>
))}
</ul>
</>
);
}Every handler is now one line, and the reducer reads like a list of everything that can happen. Name action types after what happened ("added", "toggled"), not what to do ("setTodos").
Every change is an action
Try itaction log · newest first
- Tick, delete or add a todo.
Keep the reducer pure
React calls your reducer during rendering, so it follows the same rules as a component:
- No side effects. No fetching, timers or writing to
localStorage. Do those in handlers or effects. - No randomness.
Date.now()orMath.random()gives a different result each call. Create ids in the handler and put them in the action, asnextId++does above. - No mutation.
todos.push(item); return todos;returns the same array, so React sees no change and may skip the re-render. Return a new array or object, exactly as withuseState.
In development, StrictMode calls your reducer twice with the same arguments to catch impure ones.
useState or useReducer?
useState | useReducer | |
|---|---|---|
| Best for | A few independent values | Many ways to change the same state |
| Update logic lives | In each handler | In one reducer function |
| Debugging | Find which handler did it | Log the action at the top of the reducer |
| Testing | Render the component | Call todosReducer(state, action) in a plain test |
| Code size | Smaller | A bit more up front |
Both are fine. Start with useState, and switch when the handlers start to look alike or a bug makes you hunt through all of them. You can mix the two in one component.
How it relates to Redux
If this looks like the Redux loop, it is the same idea: actions, a pure reducer, one-way flow. The differences are scope and tooling. useReducer state belongs to one component and its children; Redux is one store for the whole app, with DevTools, middleware and createSlice. Many apps use useReducer plus Context before they ever need Redux.
Two details seniors use
dispatchnever changes. It's the same function on every render, so you can pass it to children or leave it out of effect dependency arrays without problems.- Lazy initial state.
useReducer(reducer, userId, createInitialState)callscreateInitialState(userId)once on mount, instead of rebuilding an expensive starting state on every render.
Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
