React useReducer
When a component's state has many fields, or many different events update it, the update logic spreads across lots of handlers. useReducer gathers it in one place: a reducer function that receives the current state and an action describing what happened, and returns the next state.
const [state, dispatch] = useReducer(reducer, initialState);
function reducer(state, action) {
// return the next state based on action.type
}
dispatch({ type: 'added', text: 'Buy milk' });A counter with a reducer
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + state.step };
case 'decrement':
return { ...state, count: state.count - state.step };
case 'setStep':
return { ...state, step: action.step };
case 'reset':
return { count: 0, step: 1 };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
export default function App() {
const [state, dispatch] = useReducer(reducer, { count: 0, step: 1 });
return (
<div>
<p style={{ fontSize: 28, margin: 0 }}>{state.count}</p>
<button onClick={() => dispatch({ type: 'decrement' })}>−{state.step}</button>{' '}
<button onClick={() => dispatch({ type: 'increment' })}>+{state.step}</button>{' '}
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
<p>
Step:{' '}
{[1, 5, 10].map((s) => (
<label key={s} style={{ marginRight: 8 }}>
<input type="radio" checked={state.step === s} onChange={() => dispatch({ type: 'setStep', step: s })} /> {s}
</label>
))}
</p>
</div>
);
}The event handlers no longer contain logic — they only describe what happened. The reducer decides what that means.
Reducer rules
| Rule | Why |
|---|---|
| Pure: no side effects, no random values, no requests | React may call it more than once; results must be predictable |
Never mutate state — return a new object |
React compares references to detect changes |
Return the same state for unknown or no-op actions |
avoids unnecessary re-renders (or throw to catch typos) |
Actions are plain objects, usually with a type |
easy to log, test and replay |
A todo list
Reducers shine with lists, where adding, toggling, editing and deleting all touch the same array:
import { useReducer, useState } from 'react';
let nextId = 3;
const initialTodos = [
{ id: 1, text: 'Learn useState', done: true },
{ id: 2, text: 'Learn useReducer', done: false },
];
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);
case 'clearedDone':
return todos.filter((t) => !t.done);
default:
return todos;
}
}
export default function App() {
const [todos, dispatch] = useReducer(todosReducer, initialTodos);
const [text, setText] = useState('');
const remaining = todos.filter((t) => !t.done).length;
return (
<div style={{ width: 320 }}>
<form onSubmit={(e) => { e.preventDefault(); if (text.trim()) dispatch({ type: 'added', text: text.trim() }); setText(''); }}>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder="What needs doing?" />
<button>Add</button>
</form>
<ul style={{ paddingLeft: 0, listStyle: 'none' }}>
{todos.map((t) => (
<li key={t.id}>
<input type="checkbox" checked={t.done} onChange={() => dispatch({ type: 'toggled', id: t.id })} />{' '}
<span style={{ textDecoration: t.done ? 'line-through' : 'none' }}>{t.text}</span>{' '}
<button onClick={() => dispatch({ type: 'deleted', id: t.id })}>🗑</button>
</li>
))}
</ul>
<p>{remaining} left <button onClick={() => dispatch({ type: 'clearedDone' })}>Clear completed</button></p>
</div>
);
}Note:
nextId++inside the reducer is a small impurity kept for brevity. In production, create the id in the event handler and send it in the action:dispatch({ type: 'added', id: crypto.randomUUID(), text }).
Modelling a process
Reducers also make multi-step processes explicit. This simulated checkout moves through cart → paying → done (or error), and impossible transitions are simply ignored:
import { useReducer } from 'react';
const initial = { status: 'cart', error: null, attempts: 0 };
function checkoutReducer(state, action) {
switch (action.type) {
case 'pay':
if (state.status !== 'cart' && state.status !== 'error') return state;
return { ...state, status: 'paying', attempts: state.attempts + 1, error: null };
case 'paid':
return { ...state, status: 'done' };
case 'failed':
return { ...state, status: 'error', error: action.message };
case 'restart':
return initial;
default:
return state;
}
}
export default function App() {
const [state, dispatch] = useReducer(checkoutReducer, initial);
function pay() {
dispatch({ type: 'pay' });
setTimeout(() => {
// the first attempt fails, the second succeeds
if (state.attempts === 0) dispatch({ type: 'failed', message: 'Card declined (simulated)' });
else dispatch({ type: 'paid' });
}, 1000);
}
return (
<div>
<p>Status: <strong>{state.status}</strong> · attempts: {state.attempts}</p>
{state.error && <p style={{ color: 'crimson' }}>{state.error}</p>}
{(state.status === 'cart' || state.status === 'error') && <button onClick={pay}>Pay $42</button>}
{state.status === 'paying' && <p>⏳ Processing…</p>}
{state.status === 'done' && <p>✅ Thank you for your order! <button onClick={() => dispatch({ type: 'restart' })}>New order</button></p>}
</div>
);
}useState or useReducer?
Prefer useState |
Prefer useReducer |
|---|---|
| independent, simple values | several values that change together |
| one or two ways to update | many kinds of updates |
| logic is trivial | logic is worth testing on its own |
Reducers are plain functions, so you can test them without rendering anything: expect(reducer(state, { type: 'reset' })).toEqual(initial).
Tip: Combine
useReducerwith context to sharestateanddispatchwith a whole subtree — a lightweight alternative to state-management libraries.
Test yourself
What does a reducer function receive?
- Only the action
- The current state and an action
- Props and state
- The dispatch function
Which statement about reducers is true?
- They may fetch data
- They should mutate state directly for speed
- They must be pure and return a new state
- They run only once
How do event handlers update state managed by useReducer?
- By calling setState
- By calling dispatch with an action object
- By editing state.count
- By calling the reducer directly