Sub topic 2
Writing a reducer function
This chapter assumes you know JavaScript functions, objects, the spread operator, and switch statements. It also assumes you have used useState in a React component. You won't call useReducer yet. First you will write the function it depends on.
What a reducer is
A reducer is a function that takes the current state and an action, and returns the next state. The signature is always the same:
(state, action) => nextStateThe reducer holds all the rules for how state can change. It doesn't know about React, components, or the DOM. This is why you can call it directly, as the example below does.
A first reducer
Here is a counter reducer. The action argument is an object with a type field that names what happened. The next chapter covers actions in detail.
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 before = { count: 0 };
const after = counterReducer(before, { type: 'incremented' });
console.log(after); // { count: 1 }
console.log(before); // { count: 0 }The last two lines show the key behavior. The reducer returns a new object, and the original is unchanged.
Anatomy of the function
- Parameters.
stateis the value React holds now.actionis what the component reports. - A branch per action type. A
switchonaction.typeis the common convention.ifchains work too. - A return value in every branch. Whatever you return becomes the next state.
- A default branch. Throwing on an unknown type turns a typo like
'incremnted'into an immediate error. Without it, the bug passes silently.
The reducer lives outside your component. It doesn't use props or other state from the component, so it doesn't need to be redefined on every render.
Return the whole state
Each branch must return the complete next state, not only the fields that changed. This matters once state has more than one field.
function stepCounterReducer(state, action) {
switch (action.type) {
case 'incremented':
return { ...state, count: state.count + state.step };
case 'step_changed':
return { ...state, step: action.step };
default:
throw Error('Unknown action: ' + action.type);
}
}
console.log(
stepCounterReducer({ count: 0, step: 5 }, { type: 'incremented' })
); // { count: 5, step: 5 }If the first branch returned { count: state.count + state.step }, the result would lose step. The spread ...state copies every existing field, and the explicit field after it overrides one. Unlike useState, nothing merges the result for you.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Returning only the changed fields | Other fields become `undefined` | Spread the old state first: `{ ...state, count: 1 }` |
| Mutating the argument, such as `state.count++` | UI doesn't update, or updates unpredictably | Build and return a new object |
| No `default` branch | A mistyped action type does nothing | Throw an error in `default` |
| A branch with no `return` | State becomes `undefined` | Make sure every `case` returns |
| Reading or writing outside values, such as `Math.random()` or `fetch` | Results differ between calls | Pass needed data in the action |
A reducer you can reason about
Given the same state and action, a reducer should always return the same result. That property lets you test a reducer with a plain function call, and it lets React safely call the function again during development checks. You'll rely on both later.
Exercise
A reducer handles state { items: [], filter: 'all' }. The branch for 'filter_changed' is return { filter: action.filter };. What goes wrong, and how do you fix it?
Show answer
The returned object has no items field, so after this action items is undefined and components that read it will fail. Spread the old state first: return { ...state, filter: action.filter };.