useReducer and reducer design
useReducer is another React state primitive. It is useful when centralizing related state transitions makes the application easier to reason about.
Core mental modelβ
useReducer is not the βserious appβ version of useState. Use whichever model makes transitions clearer.
When useState is enoughβ
const [open, setOpen] = useState(false);
A reducer would add ceremony without improving a simple boolean transition.
Moving related transitions into a reducerβ
function tasksReducer(state, action) {
switch (action.type) {
case 'task_added':
return [
...state,
{id: action.id, text: action.text, done: false},
];
case 'task_toggled':
return state.map(task =>
task.id === action.id
? {...task, done: !task.done}
: task
);
case 'task_deleted':
return state.filter(task => task.id !== action.id);
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
function Tasks() {
const [tasks, dispatch] = useReducer(tasksReducer, []);
// ...
}
Now event handlers describe domain events instead of manually rebuilding next state everywhere.
Actions describe what happenedβ
Prefer event-shaped actions:
dispatch({
type: 'task_added',
id: crypto.randomUUID(),
text,
});
React does not require {type: ...}; it is a useful convention because structured action objects are easy to log, type, test, and inspect.
Reducers are pure calculationsβ
Reducers should not perform network requests, analytics, timers, DOM mutation, storage writes, or other side effects.
Bad:
function reducer(state, action) {
if (action.type === 'order_submitted') {
fetch('/api/orders', {method: 'POST'}); // β
}
return state;
}
Reducer logic can run during rendering, so purity matters.
Do not mutate reducer stateβ
Bad:
case 'task_toggled': {
const task = state.find(task => task.id === action.id);
task.done = !task.done;
return state;
}
Better:
case 'task_toggled':
return state.map(task =>
task.id === action.id
? {...task, done: !task.done}
: task
);
One domain event may update several fieldsβ
case 'submission_succeeded':
return {
...state,
status: 'success',
error: null,
orderId: action.orderId,
};
Do not dispatch three setter-like actions merely because three fields change. Model one transition when one domain event changed them together.
Reducers can expose poor state modellingβ
If several booleans must always be synchronized:
{
isLoading,
isSuccess,
isError,
}
consider a single status:
{
status: 'idle' | 'loading' | 'success' | 'error'
}
A reducer does not fix a weak state model automatically.
useReducer signatureβ
const [state, dispatch] = useReducer(reducer, initialArg, init?);
React gives you the current state snapshot and a stable dispatch function.
Lazy initializationβ
function createInitialState(products) {
return {
products,
selectedIds: new Set(),
};
}
const [state, dispatch] = useReducer(
reducer,
products,
createInitialState,
);
Use the initializer when creating initial state is expensive or when the initial argument needs transformation.
Props are not automatically reducer stateβ
function Editor({document}) {
const [state, dispatch] = useReducer(reducer, document);
}
Later document prop changes do not automatically reset reducer state. Decide explicitly whether you need one-time initialization, a controlled model, an explicit reset action, a key-based identity reset, or derived values instead of copied state.
Dispatch queues a future state snapshotβ
function handleClick() {
dispatch({type: 'incremented'});
console.log(state.count);
}
The current event handler still sees the current render's state snapshot.
Reducer debuggingβ
Every transition has a powerful debugging shape:
A temporary debug wrapper can log action, previousState, and nextState. Reducers are also straightforward to unit-test because transition logic is pure.
When useReducer helpsβ
Good signals include:
- several handlers perform related transitions;
- state has meaningful domain events;
- update bugs come from duplicated transition logic;
- next state depends on multiple current fields;
- central transition rules improve clarity;
- the transition function is valuable to test independently.
Event handlers and reducers have different jobsβ
The reducer should not know about DOM event objects.
Side effects happen outside the reducerβ
async function handleSave() {
dispatch({type: 'save_started'});
try {
const result = await saveOrder(state.order);
dispatch({type: 'save_succeeded', orderId: result.id});
} catch (error) {
dispatch({type: 'save_failed', message: error.message});
}
}
React 19 Actions provide another mutation model later in the handbook; they do not change reducer purity.
Reducer invariantsβ
Senior-level reducer design often centres on rules that must remain true after every transition, for example:
- success requires an
orderId; - editing state has no submission error;
- quantity can never fall below
1.
The reducer is a natural boundary for ensuring each action preserves those invariants.
File boundariesβ
A feature may keep cartReducer.js, selectors, and optional action helpers near the UI that owns them. Do not create Redux-style boilerplate around local useReducer unless it solves a real problem.
Exerciseβ
Build a checkout reducer supporting customer changes, shipping selection, submit start/success/failure, and reset. Explain why each action describes a domain event rather than a setter.
Interview questionsβ
Junior: How is useReducer different from useState?
Mid-level: Why must reducers be pure and immutable?
Senior: What makes a good action model, and when does moving logic into a reducer improve architecture rather than just add boilerplate?
Summaryβ
Use reducers for clearer transitions, not because the application crossed an arbitrary size threshold.
Referencesβ
- https://react.dev/learn/extracting-state-logic-into-a-reducer
- https://react.dev/reference/react/useReducer
Nextβ
Continue with Reducer + Context Architecture.