Introduction
As a component grows, its state updates spread out: one handler adds a task, another toggles it, a third deletes it, each with its own setTodos(...) call. With many kinds of change the logic becomes hard to follow and to test. A reducer collects every way the state can change into one function. Event handlers only say what happened; the reducer says how the state changes because of it.
How it works
Instead of calling setters, handlers dispatch actions: plain objects with a type and whatever data the change needs.
dispatch({ type: "added", id: nextId++, text });
dispatch({ type: "toggled", id: task.id });
dispatch({ type: "deleted", id: task.id });
The reducer receives the current state and an action and returns the next state. A switch on the action type is the usual shape:
function todosReducer(todos, action) {
switch (action.type) {
case "added":
return [...todos, { id: action.id, text: action.text, done: false }];
case "deleted":
return todos.filter((t) => t.id !== action.id);
default:
throw new Error("Unknown action: " + action.type);
}
}
useReducer(reducer, initialState) returns the current state and dispatch. When you dispatch, React calls the reducer with the current state and the action, stores what it returns and renders the component again.
A reducer must be pure: given the same state and action it returns the same result, and it changes nothing. It must not modify the state it receives (return new arrays and objects, as with useState), start timers or fetch data. That purity is what makes reducers easy to test: call the function with a state and an action, and check what comes back, with no React involved. Unique ids and other values that differ each time are created in the event handler and put into the action.
When should you use a reducer? useState is simpler for a few independent values. A reducer pays off when one piece of state has many kinds of update, when the next state depends on the previous one in complicated ways, or when you want the update logic in one tested place. Name actions after what happened ("added", "deleted"), not after the setter you would have called.
Example
Line by line
todosReducerhandles three actions, each returning a new array; an unknown type is a bug, so it throws.useReducerstarts the list with two tasks and gives backtodosanddispatch.- Submitting the form dispatches
addedwith a new id; the input text is ordinary state. - The checkbox dispatches
toggled, and the Delete buttondeleted. - The number left is derived from the list during render.
Expected result
The preview lists "Learn JSX" (done) and "Learn reducers", with "1 left to do". Adding "Practise" appends it and empties the input; ticking "Learn reducers" and deleting "Learn JSX" leaves "Learn reducers" and "Practise" with "1 left to do".
In the real world
Reducers are the core of Redux, the long-popular state library, and of many apps' shopping carts, editors and multi-step forms. Because they are plain functions, teams test them heavily with many small cases. Combined with context, a reducer can manage the state of a whole screen, with any component able to dispatch actions.
Common mistakes
- Modifying the state inside the reducer, for example with push, so React does not see the change.
- Doing side effects in a reducer, such as generating random ids or saving to storage.
- Forgetting to return the state for an action, which sets it to undefined.
- Naming actions after setters ("setTodos") rather than after events ("added").
Best practices
- Keep reducers pure and test them as plain functions.
- Throw for unknown action types, so mistakes are found at once.
- Put everything the reducer needs, such as new ids, into the action.
Summary
useReducer keeps state that is managed by a reducer, a pure function from the current state and an action to the next state. Event handlers dispatch actions describing what happened, and all the update logic lives in one function that can be read and tested on its own. Reducers suit state with many kinds of updates; useState stays simpler for small, independent values.
Quick check
Key takeaways
- Event handlers dispatch actions that say what happened; the reducer decides how the state changes.
- A reducer is pure: it returns new state and never modifies the old.
- Use a reducer when state has many kinds of updates or the same update happens in many places.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.