Sub topic 6
Keeping reducers pure
This chapter assumes you can write a reducer and dispatch actions with useReducer, and that you know why state updates must not mutate objects. It explains what "pure" means for a reducer, why React checks it, and the mistakes that break it.
What pure means
A reducer is pure when two conditions hold:
- The same state and action always produce the same result.
- Running it changes nothing outside itself. It does not mutate its arguments, call APIs, read the clock, or generate random values.
React relies on this. During rendering, React may call your reducer more than once for the same action, and it expects each call to give the same answer.
Strict Mode double invocation
In development, Strict Mode calls reducers twice for each dispatched action. React ignores one of the two results. This is a check and it does not happen in production. If your reducer is pure, both calls return equal values and you see no difference. If it is impure, the two calls disagree and the bug shows up right away.
A mutating reducer
This reducer mutates the array it receives.
function badReducer(todos, action) {
switch (action.type) {
case 'added':
todos.push({ id: action.id, text: action.text, done: false });
return todos;
default:
throw Error('Unknown action: ' + action.type);
}
}Two things go wrong. Under Strict Mode, push runs twice on the same array, so every todo appears twice. Also, the function returns the same array reference, so React sees no change and may skip the re-render.
The fix is to return a new array.
function todosReducer(todos, action) {
switch (action.type) {
case 'added':
return [...todos, { id: action.id, text: action.text, done: false }];
default:
throw Error('Unknown action: ' + action.type);
}
}Calling this twice with the same input gives two equal arrays, and the original is untouched.
Hidden impurity
Mutation is the obvious problem. These are easier to miss:
| Pattern inside a reducer | Why it breaks purity | Where to put it instead |
|---|---|---|
| `Date.now()` or `new Date()` | Result differs on every call | Read it in the event handler and pass it in the action |
| `Math.random()` or `crypto.randomUUID()` | Result differs on every call | Generate it in the handler and pass it in the action |
| `fetch(...)` or `localStorage.setItem(...)` | Side effect that runs twice | A `useEffect` or an event handler |
| `console.log` for debugging | Logs twice in Strict Mode | Fine for debugging, but remove it afterward |
| Reading a variable outside the function that changes | Output depends on hidden input | Put the value in state or the action |
The to-do example from earlier chapters follows this rule. It takes id from the action instead of calling a generator inside the reducer.
let nextId = 0;
// In the event handler, not the reducer:
dispatch({ type: 'added', id: nextId++, text });If the reducer incremented nextId itself, the double call would skip every other id.
function wrongReducer(todos, action) {
if (action.type === 'added') {
// Impure: reads and changes a variable outside the function
return [...todos, { id: nextId++, text: action.text, done: false }];
}
return todos;
}Side effects belong elsewhere
A reducer only describes how state changes. Work that touches the outside world goes in event handlers or in useEffect. In the fetch example, the effect calls fetch and then dispatches fetch_started, fetch_succeeded, or fetch_failed. The reducer records what happened and does nothing else.
Checking purity quickly
Ask three questions about each case in your reducer:
- Does it change
stateoractionin place, for example withpush,splice, orstate.x = ...? - Does it call something whose result can differ between calls?
- Does it do anything besides compute and return the next state?
If any answer is yes, move that work out or copy before changing.
Exercise
A reducer handles { type: 'added', text } by returning [...todos, { id: Date.now(), text, done: false }]. Is it pure? If not, how do you fix it?
Show answer
It is not pure. Date.now() returns a different value on each call, so Strict Mode's two calls produce different ids and the discarded result differs from the kept one. Call Date.now() (or a counter) in the event handler and dispatch { type: 'added', id, text }. The reducer then reads action.id.
Exercise
Why can a reducer that calls state.items.push(action.item) and returns state both duplicate items and fail to re-render?
Show answer
In Strict Mode the reducer runs twice on the same object, so push adds the item twice. It also returns the same reference it received, so React sees no change in state and can skip the re-render. Return a new object with a new array, such as { ...state, items: [...state.items, action.item] }.