Sub topic 2
Writing a reducer function
What this chapter assumes
You should be comfortable with JavaScript functions, objects, arrays, and the spread operator. You should also know React function components and the useState hook. This chapter covers only the reducer function. Later chapters cover action design, immutable updates, purity rules, and the useReducer hook in detail. Here you learn the shape a reducer must have and the mistakes that break it.
The contract: (state, action) => nextState
A reducer is a plain JavaScript function with a fixed contract:
- It receives the current state.
- It receives an action, which is a description of what happened.
- It returns the next state.
Nothing else is allowed to be part of the contract. The reducer does not receive setState, props, or the component. It does not return a value for React to ignore. Whatever it returns becomes the new state.
function counterReducer(state, action) {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'decremented':
return { count: state.count - 1 };
case 'reset':
return { count: 0 };
default:
throw Error('Unknown action: ' + action.type);
}
}
const s0 = { count: 0 };
const s1 = counterReducer(s0, { type: 'incremented' });
const s2 = counterReducer(s1, { type: 'incremented' });
const s3 = counterReducer(s2, { type: 'reset' });
console.log(s1, s2, s3); // { count: 1 } { count: 2 } { count: 0 }This file runs in Node with no React installed. A reducer does not depend on React, and that independence is the main reason to use one.
The same idea as Array.reduce
The name comes from Array.prototype.reduce. A reduce callback takes an accumulated value and one item, and returns the new accumulated value. A reducer does the same thing with the state as the accumulator and an action as the item.
function counterReducer(state, action) {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'decremented':
return { count: state.count - 1 };
default:
throw Error('Unknown action: ' + action.type);
}
}
const history = [
{ type: 'incremented' },
{ type: 'incremented' },
{ type: 'decremented' },
];
const finalState = history.reduce(counterReducer, { count: 0 });
console.log(finalState); // { count: 1 }This view explains two properties. The current state is the result of applying every past action in order to the initial state. Given the same starting state and the same actions, you always get the same result.
Where to define the reducer
Define the reducer outside your component, at module level. It does not need props or hooks, so nothing ties it to a render.
- A reducer defined outside is created once. A reducer defined inside the component is recreated on every render.
- A module-level reducer can be exported and tested without rendering anything.
- A reducer defined outside cannot accidentally close over props or other state. A reducer defined inside can read those values without you noticing. They may be stale or differ between renders, which makes the reducer harder to reason about.
If the reducer genuinely needs a value from props, put that value in the action instead.
Anatomy of a switch-based reducer
Most React code writes reducers as a switch on action.type. Each part has a job.
switch (action.type)picks the branch. You could useifstatements, and React accepts any function with the right contract.switchis the convention, so other developers will expect it.- One
caseper kind of event. Name cases for what happened, such as'added','toggled', or'fetch_failed', not for the setter you wish to call. The next chapter covers action naming. - Every branch returns. A
returninside each case also prevents fall-through, so you do not needbreak. - A
defaultbranch handles action types the reducer does not recognize.
When a case needs a local variable, wrap the case body in braces. Without braces, a const declared in one case is scoped to the whole switch block, and a second declaration with the same name raises a SyntaxError.
function todosReducer(todos, action) {
switch (action.type) {
case 'added': {
const todo = { id: action.id, text: action.text, done: false };
return [...todos, todo];
}
case 'deleted': {
const remaining = todos.filter(t => t.id !== action.id);
return remaining;
}
default:
throw Error('Unknown action: ' + action.type);
}
}
let todos = [];
todos = todosReducer(todos, { type: 'added', id: 1, text: 'Write a reducer' });
todos = todosReducer(todos, { type: 'added', id: 2, text: 'Test it' });
todos = todosReducer(todos, { type: 'deleted', id: 1 });
console.log(todos); // [ { id: 2, text: 'Test it', done: false } ]Returning the whole next state
The most common beginner error is returning only the part of the state that changed. React does not merge the returned value into the old state. It replaces the old state with whatever you return. This differs from the class component this.setState, which did merge.
When the state is an object with several fields, copy the unchanged fields into the returned object. Spread does this.
const initialForm = { name: '', email: '', submitted: false };
function formReducer(form, action) {
switch (action.type) {
case 'field_changed':
return { ...form, [action.field]: action.value };
case 'submitted':
return { ...form, submitted: true };
case 'cleared':
return initialForm;
default:
throw Error('Unknown action: ' + action.type);
}
}
let form = initialForm;
form = formReducer(form, { type: 'field_changed', field: 'name', value: 'Ada' });
form = formReducer(form, { type: 'field_changed', field: 'email', value: '[email protected]' });
form = formReducer(form, { type: 'submitted' });
console.log(form);
// { name: 'Ada', email: '[email protected]', submitted: true }
form = formReducer(form, { type: 'cleared' });
console.log(form); // { name: '', email: '', submitted: false }Three details in this code are worth noting:
{ ...form, submitted: true }keepsnameandemailand overridessubmitted. Writingreturn { submitted: true }would erase the other two fields.[action.field]is a computed property name. Onefield_changedcase handles every text field, which avoids a separate case for each input.'cleared'returns theinitialFormconstant. Returning a shared constant is safe only because reducers never modify the state they receive.
Returning the same state when nothing changes
A reducer may return the exact state object it received. This is the right answer when an action does not apply, for example when a 'toggled' action names an id that does not exist.
function toggleReducer(todos, action) {
switch (action.type) {
case 'toggled': {
const exists = todos.some(t => t.id === action.id);
if (!exists) return todos; // same reference, nothing changed
return todos.map(t => (t.id === action.id ? { ...t, done: !t.done } : t));
}
default:
throw Error('Unknown action: ' + action.type);
}
}
const before = [{ id: 1, text: 'Read', done: false }];
const same = toggleReducer(before, { type: 'toggled', id: 99 });
console.log(same === before); // trueWhen the returned value is identical (Object.is) to the current state, React can skip re-rendering the children. Returning a fresh copy that looks the same would cause extra work. How React uses this comparison is covered in the chapter on dispatch behavior.
The default case: throw or return state
Every reducer must decide what to do with an action type it does not handle. There are two common choices.
| Choice | Code | Effect | When to use it |
|---|---|---|---|
| Throw | `throw Error('Unknown action: ' + action.type)` | A typo in an action type fails loudly during development | Default choice for application reducers |
| Return state | `return state` | Unknown actions are silently ignored | When several reducers deliberately share one stream of actions |
Throwing is the safer default. Without it, a misspelled dispatch({ type: 'incrmented' }) does nothing, and you have to find the typo by reading. With it, the error message names the bad type.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| State becomes `undefined` and the next render crashes with "Cannot read properties of undefined" | A case computes a value but has no `return`, or the `default` branch is missing and no case matched | Return in every branch and add a `default` |
| Some fields disappear after one action | The case returned only the changed fields | Spread the old state first: `{ ...state, changed: value }` |
| `SyntaxError: Identifier 'x' has already been declared` | Two cases declare the same `const` without braces | Wrap each case body in `{ }` |
| The UI does not update after an action | The case changed the existing object and returned it | Return a new object or array |
| A case reads `action.value` but gets `undefined` | The dispatching code used a different field name | Agree on action fields and keep them consistent |
| Error thrown with an unfamiliar type name | A component dispatched a type the reducer does not list | Fix the typo, or add the case |
A checklist for a new reducer
- Decide the shape of the state, and write the initial state next to the reducer.
- List the events that can happen, and give each a past-tense name.
- Write one
caseper event. Each returns a complete next state. - Add a
defaultthat throws. - Call the reducer by hand in a scratch file, as in the examples above, before wiring it into a component.
Step 5 is cheap because the reducer is a plain function. If it gives the wrong output in a scratch file, it will give the wrong output in React.
Exercise
This reducer manages { name: '', age: 0 }. After dispatch({ type: 'age_changed', value: 30 }), the name field becomes undefined. What is wrong, and what is the corrected age_changed case?
function profileReducer(state, action) {
switch (action.type) {
case 'age_changed':
return { age: action.value };
default:
throw Error('Unknown action: ' + action.type);
}
}
Show answer
The case returns an object containing only age. React replaces the old state with the returned value and does not merge, so name is lost. Copy the existing fields first: case 'age_changed': return { ...state, age: action.value };
Exercise
A reducer has two cases that each begin with const next = ... and no braces around the case bodies. What happens, and how do you fix it?
Show answer
JavaScript raises a SyntaxError because both const next declarations are scoped to the same switch block. Wrap each case body in braces, as in case 'added': { const next = ...; return next; }, so each declaration has its own scope.