Sub topic 6
Keeping reducers pure
This chapter assumes you can already write a reducer with a switch on action.type, dispatch actions from event handlers, and copy objects and arrays with spread, map, and filter. Here you will learn what "pure" means for a reducer, why React checks it for you in development, and how to fix the usual violations.
What React expects from a reducer
React calls your reducer while it renders the component, not at the moment you call dispatch. When you dispatch, React queues the action. During the next render it runs the reducer with the current state and each queued action to compute the new state. The reducer is therefore part of rendering, and React's rules for rendering apply to it.
A pure reducer follows two rules:
- Same inputs, same output. Given the same
stateandaction, it always returns the same result. It does not read the clock, a random number generator, or a variable defined outside the function. - No side effects. It does not change anything outside itself. It does not mutate its arguments, write to storage, call the network, log to a server, or dispatch other actions.
React depends on these rules because it may call the reducer more than once for one dispatch. It can discard a render and start over, or re-run the reducer after other updates arrive. If the reducer is pure, repeating a call is harmless. If it is not, repeating a call produces duplicated or inconsistent state.
| Allowed in a reducer | Not allowed in a reducer |
|---|---|
| Reading `state` and `action` | Reading `Date.now()`, `Math.random()`, or `crypto.randomUUID()` |
| Returning new objects and arrays | Mutating `state` or `action` (`push`, `splice`, `state.x = ...`) |
| Calling other pure helper functions | `fetch`, `localStorage`, `console` calls that matter, timers |
| Throwing for an unknown action type | Calling `dispatch` or a `setState` function |
| Reading constants defined outside | Reading or writing mutable variables defined outside |
How Strict Mode checks for you
In development, wrapping your app in <StrictMode> makes React call each reducer twice per action, with the same arguments. React uses one result and discards the other. Production builds do not do this.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);A pure reducer cannot tell the difference, because two calls with the same inputs return equal results. An impure reducer shows the problem right away, usually as duplicated items or values that jump by twice what you expected.
The double call is a test, not a bug. Treat a doubled effect in development as a warning that the reducer has a side effect.
Violation 1: mutating state
Mutation is the most common mistake. This reducer looks reasonable but is wrong:
function badTodosReducer(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);
}
}This code has two problems:
- Duplicates under Strict Mode. Both calls receive the same array, so the second
pushadds the item again. The list shows two copies of every new todo. - No re-render. The function returns the same array reference. React compares the new state with the old state using
Object.is. Because the reference is identical, React concludes nothing changed and may skip the render. The UI updates later, when something else triggers a render, which makes the bug hard to trace.
The fix is to return a new array and leave the old one alone:
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);
}
}The same rule applies to nested data. Copying the top-level object is not enough if you then change an inner object. Copy every level you change, and reuse the levels you do not.
function profileReducer(profile, action) {
switch (action.type) {
case 'city_changed':
return {
...profile,
address: { ...profile.address, city: action.city },
};
default:
throw Error('Unknown action: ' + action.type);
}
}Violation 2: non-deterministic values
Reading the clock or a random source inside the reducer breaks the "same inputs, same output" rule. This version generates an id with a module-level counter:
let nextId = 0;
function badReducer(todos, action) {
switch (action.type) {
case 'added':
return [...todos, { id: nextId++, text: action.text, done: false }];
default:
throw Error('Unknown action: ' + action.type);
}
}Under Strict Mode the reducer runs twice per action, so nextId advances by 2 and ids skip numbers. Date.now() and crypto.randomUUID() give different values on each call, so the two results differ and React discards one of them.
The fix is to produce the value in the event handler, which runs once per user action, and carry it in the action. The reducer then only copies data from the action into state. This complete component stores notes with an id and a creation time:
import { useReducer, useState } from 'react';
function notesReducer(notes, action) {
switch (action.type) {
case 'added':
return [
...notes,
{ id: action.id, text: action.text, createdAt: action.createdAt },
];
case 'deleted':
return notes.filter(n => n.id !== action.id);
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Notes() {
const [notes, dispatch] = useReducer(notesReducer, []);
const [text, setText] = useState('');
function handleAdd() {
dispatch({
type: 'added',
id: crypto.randomUUID(),
text,
createdAt: Date.now(),
});
setText('');
}
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<button onClick={handleAdd}>Add note</button>
<ul>
{notes.map(n => (
<li key={n.id}>
{n.text} ({new Date(n.createdAt).toLocaleTimeString()})
<button onClick={() => dispatch({ type: 'deleted', id: n.id })}>
Delete
</button>
</li>
))}
</ul>
</>
);
}Moving the impure call into the handler also makes the reducer easier to test, because the action contains everything the reducer needs.
Violation 3: side effects
A side effect is any work that changes something outside the function or depends on something outside it. Three examples of effects that do not belong in a reducer are saving to localStorage, calling fetch, and dispatching a second action.
function badReducer(notes, action) {
switch (action.type) {
case 'deleted': {
const next = notes.filter(n => n.id !== action.id);
localStorage.setItem('notes', JSON.stringify(next)); // side effect
return next;
}
default:
throw Error('Unknown action: ' + action.type);
}
}In development this write runs twice per delete. In production it can still run for renders that React later throws away, so storage can hold a state that never appeared on screen.
Put the effect where React expects it. Either run it in the event handler, or synchronize it from state with useEffect:
import { useEffect } from 'react';
// Inside the Notes component, after useReducer:
useEffect(() => {
localStorage.setItem('notes', JSON.stringify(notes));
}, [notes]);The effect runs after React commits the render, only for states that actually reached the screen, and only when notes changes.
Violation 4: reading changing outside data
A reducer should depend only on its two arguments. This one reads a mutable variable from outside:
let discount = 0.1; // changed elsewhere in the app
function cartReducer(cart, action) {
switch (action.type) {
case 'item_added':
return {
...cart,
total: cart.total + action.price * (1 - discount),
};
default:
throw Error('Unknown action: ' + action.type);
}
}If discount changes between React's two calls, or between a discarded render and the real one, the same action yields different totals. Carry the value in the action (action.discount) or store it in state.
Constants that never change, such as a lookup table or const MAX_ITEMS = 10, are fine to read.
Checking purity in a test
Because a reducer is a plain function, you can verify its purity without rendering anything. Freeze the input so any mutation throws, then call the reducer twice and compare the results.
import { describe, it, expect } from 'vitest';
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);
}
}
describe('todosReducer purity', () => {
it('does not mutate its input and is repeatable', () => {
const before = Object.freeze([
Object.freeze({ id: 1, text: 'First', done: false }),
]);
const action = { type: 'added', id: 2, text: 'Second' };
const first = todosReducer(before, action);
const second = todosReducer(before, action);
expect(first).toEqual(second);
expect(first).not.toBe(before);
expect(before).toHaveLength(1);
});
});Object.freeze is shallow, so freeze nested objects you want protected, as the inner call does above. In an ES module (strict mode), assigning to a frozen object or pushing to a frozen array throws a TypeError, so a mutating reducer fails the test.
Debugging checklist
When state looks doubled, skipped, or stale, check these causes in order:
- Mutation. Search the reducer for
push,pop,splice,sort,reverse, and assignments such asstate.x =oritem.done =. - Generated values. Search for
Date,Math.random,randomUUID, and counters likenextId++. Move them into the handler. - Side effects. Search for
fetch,localStorage,setTimeout, andconsole.logused as real output. Move them into handlers oruseEffect. - Outside reads. Look for any variable in the reducer that is neither a parameter, a local, nor a constant.
- Missing return. A
casethat falls through or returns nothing sets the state toundefined.
Exercises
Exercise
A reducer handles { type: 'added', text } with return [...todos, { id: Date.now(), text, done: false }]. Is it pure? If not, say why and show the fix.
Show answer
It is not pure. Date.now() returns a different value on each call, so two calls with the same state and action (as Strict Mode makes in development) return different results. Generate the id in the event handler and pass it in the action: dispatch({ type: 'added', id: Date.now(), text }). The reducer then returns [...todos, { id: action.id, text: action.text, done: false }].
Exercise
In development, each click on "Add" shows two identical items in your list, but production shows one. The reducer contains todos.push(item); return todos;. Explain both symptoms and fix the code.
Show answer
Strict Mode calls the reducer twice with the same array, so push runs twice and adds the item twice. Returning the same array reference also means React's Object.is check sees no change and can skip the render. The fix is to return a new array: return [...todos, item];. The old array is then never touched, so repeated calls give the same result.
Exercise
Your reducer calls localStorage.setItem after computing the next state. Where should that call go, and why?
Show answer
Move it into a useEffect with the state in its dependency array, for example useEffect(() => { localStorage.setItem('notes', JSON.stringify(notes)); }, [notes]);. The effect runs only after React commits a render that reached the screen. A reducer runs during rendering, possibly more than once and possibly for renders that are discarded, so the write could run extra times or save a state that was never shown.