Skip to main content

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​

Reducer update flowEvents describe what happened; the reducer calculates the next state.
1user / system event
2dispatch action
3reducer receives state + action
4reducer returns next state
5React renders next snapshot

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.

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,
});
Good action names explain why state changed
Event / domain language
task_added Β· checkout_started Β· shipping_address_changed Β· cart_cleared
Implementation language
set_tasks Β· set_field_7 Β· update_everything

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​

Reducer = current state + action β†’ next state
Inputs
current state + action
Output
next state

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'
}
Prefer representable state over conflicting flags
Three booleans
Can accidentally represent impossible combinations.
One status
Encodes one valid mode at a time.

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.

Dispatch follows the same snapshot model as useState
1current render has state A
2dispatch(action)
3React queues update
4reducer calculates state B
5future render sees state B

Reducer debugging​

Every transition has a powerful debugging shape:

Reducer transition record
Previous state
Reducer
Next state

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.
Should this local state use a reducer?
Updates are simple and obvioususeState is usually clearer
Many related handlers encode the same transition rulesuseReducer may centralize the logic well
The real problem is remote caching or global subscription granularityA reducer is solving the wrong problem

Event handlers and reducers have different jobs​

Event layer vs reducer layer
Event handler
understands browser/user event Β· prepares domain payload Β· dispatches action
Reducer
calculates next state Β· enforces transition rules Β· stays pure

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});
}
}
Async workflow around a pure reducer
1user submits
2event/action layer starts async work
3result arrives
4dispatch success/failure event
5reducer calculates next state

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​

Reducer design summary
1identify related transitions
2dispatch meaningful events
3pure reducer calculates next state
4React renders next snapshot

Use reducers for clearer transitions, not because the application crossed an arbitrary size threshold.

References​

Next​

Continue with Reducer + Context Architecture.