useReducer
Overview
As components grow, state updates spread across many event handlers: add an item here, remove one there, change a quantity, clear everything. Each handler contains a little piece of logic, and understanding how the state can change means reading all of them. useReducer moves all that logic into one function — a reducer — outside the component.
From setState to dispatch
With useState, handlers say what the new state is:
function handleAdd(text) {
setTasks([...tasks, { id: nextId++, text, done: false }]);
}
function handleToggle(id) {
setTasks(tasks.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}
function handleDelete(id) {
setTasks(tasks.filter((t) => t.id !== id));
}With useReducer, handlers say what happened, by dispatching an action:
function handleAdd(text) {
dispatch({ type: 'added', id: nextId++, text });
}
function handleToggle(id) {
dispatch({ type: 'toggled', id });
}
function handleDelete(id) {
dispatch({ type: 'deleted', id });
}And one reducer function decides how each action changes the state:
function tasksReducer(tasks, action) {
switch (action.type) {
case 'added':
return [...tasks, { id: action.id, text: action.text, done: false }];
case 'toggled':
return tasks.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
case 'deleted':
return tasks.filter((t) => t.id !== action.id);
default:
throw new Error(`Unknown action: ${action.type}`);
}
}Wiring it up
import { useReducer } from 'react';
let nextId = 3;
const initialTasks = [
{ id: 1, text: 'Watch the hooks lesson', done: true },
{ id: 2, text: 'Do the exercise', done: false },
];
export function TaskApp() {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
return (
<>
<AddTask onAdd={(text) => dispatch({ type: 'added', id: nextId++, text })} />
<TaskList
tasks={tasks}
onToggle={(id) => dispatch({ type: 'toggled', id })}
onDelete={(id) => dispatch({ type: 'deleted', id })}
/>
</>
);
}useReducer takes the reducer and the initial state, and returns the current state plus a dispatch function. When you call dispatch(action), React calls tasksReducer(currentState, action), stores the result and re-renders.
Writing good reducers
Reducers must be pure. Like components, they run during rendering (React may call them more than once in development). So inside a reducer:
- don’t mutate
state— return new objects and arrays, - don’t make requests, set timeouts, or read random values or the time,
- do compute the next state from
stateandactionalone.
That’s why the id is generated in the handler (nextId++) and passed in the action, rather than inside the reducer.
Actions describe events, not setters. Prefer { type: 'itemAddedToCart' } over { type: 'setItems', items }. Event-style actions keep the logic in the reducer and make the history of actions readable in debugging tools.
Each case returns state. Use { ... } blocks around cases that declare variables, so names don’t clash between cases. Throwing on unknown actions catches typos immediately.
Reducers with object state
Reducers often manage an object with several fields:
const initialState = { status: 'idle', results: [], error: null, page: 1 };
function searchReducer(state, action) {
switch (action.type) {
case 'started':
return { ...state, status: 'loading', error: null };
case 'succeeded':
return { ...state, status: 'success', results: action.results };
case 'failed':
return { ...state, status: 'error', error: action.error };
case 'nextPage':
return { ...state, page: state.page + 1 };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}Notice how each action updates several related fields at once — consistently. With separate useState calls, every handler would have to remember to update all of them.
Testing reducers
A reducer is a plain function, so you can test it without rendering anything:
import { test, expect } from 'vitest';
import { tasksReducer } from './tasksReducer.js';
test('toggling a task flips done', () => {
const state = [{ id: 1, text: 'A', done: false }];
const next = tasksReducer(state, { type: 'toggled', id: 1 });
expect(next[0].done).toBe(true);
expect(state[0].done).toBe(false); // original untouched
});useState or useReducer?
useState |
useReducer |
|
|---|---|---|
| Code size | less for simple state | more upfront; less as handlers multiply |
| Readability | great for independent values | great when updates are related |
| Debugging | console.log in many handlers |
one place to log every action |
| Testing | test through the component | test the reducer in isolation |
Use useState by default. Switch to useReducer when a component has many handlers modifying the same state, when one event changes several values together, or when you find bugs caused by state updates spread across the component. You can mix both in the same component.
Lazy initial state
Like useState, useReducer accepts an initialiser function as a third argument to compute the initial state once:
const [state, dispatch] = useReducer(cartReducer, userId, (id) => loadCartFromStorage(id));Looking ahead
Reducers pair naturally with context: put state and dispatch in context, and any component deep in the tree can read the state or dispatch actions — a lightweight alternative to a state-management library. That’s Context with reducer, in the Sharing state chapter.
Tip: you can use the Immer library’s
useImmerReducerto write reducers in a “mutating” style (draft.items.push(item)) that still produces immutable updates — handy for deeply nested state.
A shopping cart reducer
Write cartReducer(state, action) for a cart state { items: [] } where each item is { id, title, price, qty }. Support actions added (adds an item with qty 1, or increments qty if it’s already there), removed (by id), qtyChanged ({ id, qty } — removes the item if qty is 0) and cleared. Throw an error for unknown actions. Then use it in a Cart component with useReducer.
export function cartReducer(state, action) {
// your code here
}import { useReducer } from 'react';
export function cartReducer(state, action) {
switch (action.type) {
case 'added': {
const existing = state.items.find((i) => i.id === action.item.id);
if (existing) {
return {
...state,
items: state.items.map((i) => (i.id === action.item.id ? { ...i, qty: i.qty + 1 } : i)),
};
}
return { ...state, items: [...state.items, { ...action.item, qty: 1 }] };
}
case 'removed':
return { ...state, items: state.items.filter((i) => i.id !== action.id) };
case 'qtyChanged':
if (action.qty <= 0) {
return { ...state, items: state.items.filter((i) => i.id !== action.id) };
}
return {
...state,
items: state.items.map((i) => (i.id === action.id ? { ...i, qty: action.qty } : i)),
};
case 'cleared':
return { ...state, items: [] };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
export function Cart({ catalogue }) {
const [cart, dispatch] = useReducer(cartReducer, { items: [] });
const total = cart.items.reduce((sum, i) => sum + i.price * i.qty, 0);
return (
<div>
{catalogue.map((c) => (
<button key={c.id} onClick={() => dispatch({ type: 'added', item: c })}>
Add {c.title}
</button>
))}
<ul>
{cart.items.map((i) => (
<li key={i.id}>
{i.title} × {i.qty}
<button onClick={() => dispatch({ type: 'removed', id: i.id })}>Remove</button>
</li>
))}
</ul>
<p>Total: ${total.toFixed(2)}</p>
<button onClick={() => dispatch({ type: 'cleared' })}>Clear cart</button>
</div>
);
}Summary
useReducer(reducer, initialState)returns[state, dispatch]; you dispatch actions instead of setting state.- A reducer is a pure function
(state, action) => nextStatethat lives outside the component. - Actions describe what happened, e.g.
{ type: 'added', item }; the reducer decides how state changes. - Reducers must not mutate state or have side effects, and must return state for every action.
- Use a reducer when many handlers update the same state in related ways;
useStateis fine otherwise.