useReducer for complex state
When state logic outgrows useState, the reducer pattern of state, action, and dispatch, the useState vs useReducer tradeoff, and a worked todo-list example.
useReducer for complex state
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- useReducer replaces several related setX calls scattered through a component with one dispatch function and one reducer function that decides, in a single place, how every kind of update changes the state.
- A reducer is a plain function, `(state, action) => newState`, that takes the current state and a description of what happened and returns the next state — it never mutates the state it's given.
- An action is typically an object with a `type` field describing what happened (like "added" or "toggled") and whatever extra data the reducer needs to apply that change.
- `dispatch(action)` is the only thing components call to request a change; they describe what happened, and the reducer alone decides how that translates into a new state.
- useState is usually simpler and enough for one or two independent values; useReducer earns its extra ceremony once several related pieces of state update together, or update the same way from several different places in the UI.
- Centralizing update logic in a reducer makes it testable on its own, as a plain function, completely separate from any component or rendering concern.
When useState starts to strain
useState works well when a component tracks a handful of independent values, each updated by its own small piece of logic. It starts to strain once several pieces of state change together, or the same kind of update needs to happen from multiple places with shared rules for what’s allowed. A todo list is the classic example: adding, toggling, and deleting all change the same array, each with its own quirks, and scattering that logic across three separate handlers each calling setTodos directly tends to drift out of sync.
useReducer centralizes that logic instead. Rather than many places calling a setter directly, one function — the reducer — owns every rule for how state can change, and every part of the component calls the same dispatch function to request a change, describing what happened rather than how to apply it.
The three pieces: state, action, dispatch
import { useReducer } from "react";
function counterReducer(state, action) {
switch (action.type) {
case "incremented":
return { count: state.count + 1 };
case "decremented":
return { count: state.count - 1 };
case "reset":
return { count: 0 };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "incremented" })}>+1</button>
<button onClick={() => dispatch({ type: "decremented" })}>-1</button>
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
);
}
useReducer(reducer, initialState) returns the current state and a dispatch function, mirroring useState’s [value, setValue] shape. counterReducer is a plain function: given the current state and an action object (here, just { type: "..." }), it returns the next state, always as a new object rather than a mutation of the old one. The component never computes state.count + 1 itself — it just dispatches { type: "incremented" } and trusts the reducer to know what that means.
A worked example with payload data: a small todo list
Actions often carry extra data beyond just a type, usually called a payload:
function todosReducer(todos, action) {
switch (action.type) {
case "added":
return [...todos, { id: action.id, text: action.text, done: false }];
case "toggled":
return todos.map((todo) =>
todo.id === action.id ? { ...todo, done: !todo.done } : todo
);
case "deleted":
return todos.filter((todo) => todo.id !== action.id);
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
function TodoList() {
const [todos, dispatch] = useReducer(todosReducer, []);
function handleAdd(text) {
dispatch({ type: "added", id: Date.now(), text });
}
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<input
type="checkbox"
checked={todo.done}
onChange={() => dispatch({ type: "toggled", id: todo.id })}
/>
{todo.text}
<button onClick={() => dispatch({ type: "deleted", id: todo.id })}>
Delete
</button>
</li>
))}
</ul>
);
}
Every one of “added,” “toggled,” and “deleted” touches the same todos array, but each does something structurally different — appending, mapping with a conditional change, filtering. Written as three separate setTodos calls scattered across three handlers, that’s three places that each need to remember they’re working with the same array and not accidentally mutate it. Written as one reducer, all three rules sit together in todosReducer, in plain, framework-free JavaScript you could copy into a unit test file and call directly with a sample todos array and an action object, asserting on the array it returns — no rendering, no DOM, no React at all.
Choosing between useState and useReducer
There’s no hard line, but a reasonable rule of thumb: reach for useState first, since it’s simpler to read for one or two independent values with simple updates. Switch to useReducer once you notice several pieces of state that always change together, update logic that’s getting complex enough to want its own tests, or the same kind of update being triggered from more than one place in the UI with rules you don’t want duplicated. useReducer isn’t “advanced useState” so much as a different shape for the same job — moving the decision of how state changes out of the component and into one dedicated function.
What the video covers
Codevolution’s episode introduces the reducer pattern from scratch using a simple counter, with state, action, and dispatch exactly as shown in the first example above, in current React 19 syntax. It’s the clearest on-ramp for seeing the three pieces fit together, but it doesn’t address the useState-vs-useReducer tradeoff directly or scale to a multi-field example — the todo-list walkthrough above, and the linked follow-on episode on complex state and actions, cover that ground.
Where this fits
This closes out the state, events, and forms group. Next, the roadmap turns to synchronizing a component with the world outside React — covered starting with the component lifecycle with hooks.
Check yourself
What are the two arguments a reducer function takes, and what must it return?
A reducer takes the current state and an action describing what happened, and it must return the new state without mutating the state object it was given. Its signature is (state, action) => newState.
What does calling dispatch({ type: "incremented" }) actually do?
It does not change state directly. It hands that action object to the reducer function along with the current state, and React replaces the stored state with whatever the reducer returns for that combination. The component that called dispatch never decides how the increment is applied — only that an "incremented" event happened.
You have a form with five related fields that need to update together through shared validation logic. Is useState or useReducer the better fit, and why?
useReducer is the better fit here. Five related values with shared update logic are exactly the case where scattering five separate setX calls (and the validation logic that has to run alongside each) across the component gets unwieldy; centralizing that logic in one reducer function, dispatched to from one place, keeps the update rules in a single, testable location.
Why is a reducer easier to unit test than equivalent logic spread across several useState calls and handlers?
A reducer is a plain JavaScript function — given a state and an action, it returns a new state, with no dependency on React rendering, hooks, or the DOM. You can call it directly in a test with sample states and actions and assert on its return value, without rendering a component at all.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.