Sub topic 11
Moving update logic into a reducer
This chapter assumes you have the to-do app from the earlier chapters. It has a todos array in useState, immutable updates with map, filter and spread, and the state lifted into App. You should be comfortable with switch statements and array methods.
Why move logic out of event handlers
By now App has several functions that each call setTodos in a different way: add, toggle, delete. Editing, which you built in the previous chapter, adds a fourth. Each function is small, but the rules for how the list may change are scattered across the component. To learn what the list can do, you have to read every handler.
A reducer collects those rules in one place. A reducer is a pure function that takes the current state and an action, and returns the next state. An action is a plain object that describes what happened, such as { type: "toggled", id }. Components no longer say how to change the list. They say what happened, and the reducer decides the result.
React provides the useReducer hook for this pattern.
The reducer function
function todosReducer(todos, action) {
switch (action.type) {
case "added":
return [...todos, { id: action.id, title: action.title, done: false }];
case "toggled":
return todos.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
case "deleted":
return todos.filter((t) => t.id !== action.id);
default:
throw new Error("Unknown action: " + action.type);
}
}
// Inside a component:
// const [todos, dispatch] = useReducer(todosReducer, []);
// dispatch({ type: "added", id: crypto.randomUUID(), title: "Buy milk" });Each case uses the same immutable techniques as before. The only change is where the code lives.
The default branch throws. A misspelled action type such as "toggeled" then fails loudly during development instead of silently leaving the list unchanged.
Rules a reducer must follow
A reducer must be pure. React may call it more than once with the same inputs, for example in Strict Mode during development, and it expects the same result each time.
- Do not mutate
todosor its items. Return new arrays and objects. - Do not call
crypto.randomUUID(),Date.now()orMath.random()inside the reducer. They return a different value each call, which breaks purity. Generate the id where you dispatch, and pass it in the action, as theaddedcase above does. - Do not read or write
localStorage, send requests, or start timers. Those are side effects, and a later chapter handles them.
Replacing useState with useReducer
useReducer(reducer, initialState) returns the current state and a dispatch function. Compare the two versions of App.
import { useReducer, useState } from "react";
function todosReducer(todos, action) {
switch (action.type) {
case "added":
return [...todos, { id: action.id, title: action.title, done: false }];
case "toggled":
return todos.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
case "deleted":
return todos.filter((t) => t.id !== action.id);
default:
throw new Error("Unknown action: " + action.type);
}
}
function TodoItem({ todo, onToggle, onDelete }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
<span style={{ textDecoration: todo.done ? "line-through" : "none" }}>
{todo.title}
</span>
</label>
<button type="button" onClick={() => onDelete(todo.id)}>
Delete
</button>
</li>
);
}
export default function App() {
const [todos, dispatch] = useReducer(todosReducer, []);
const [text, setText] = useState("");
function addTodo(event) {
event.preventDefault();
const title = text.trim();
if (!title) return;
dispatch({ type: "added", id: crypto.randomUUID(), title });
setText("");
}
return (
<main>
<h1>To-do</h1>
<form onSubmit={addTodo}>
<label>
New task
<input value={text} onChange={(e) => setText(e.target.value)} />
</label>
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={(id) => dispatch({ type: "toggled", id })}
onDelete={(id) => dispatch({ type: "deleted", id })}
/>
))}
</ul>
</main>
);
}Three things stayed the same: TodoItem is unchanged, the controlled input still uses useState, and the list still uses stable keys. Only the way todos changes is different.
The text field keeps useState on purpose. It holds temporary form input, and no other part of the app needs its history. Not every piece of state belongs in the reducer.
What happens when you dispatch
dispatch does not change todos right away. As with setTodos, the new value appears on the next render. If you log todos straight after calling dispatch, you still see the old list.
React compares the returned array with the previous one using reference equality. If the reducer returns the same array, React skips the re-render. That is why a mutating reducer fails in a confusing way: it changes the array in place and returns the same reference, so the screen does not update.
Handling the edit action
The inline editing chapter changed a to-do's title. In a reducer, this is one more case.
case "edited":
return todos.map((t) =>
t.id === action.id ? { ...t, title: action.title } : t
);Dispatch it with dispatch({ type: "edited", id, title: newTitle }). Notice that adding a feature touched the reducer and the one place that dispatches. No other handler needed to change.
Comparing useState and useReducer
| Situation | Better fit |
|---|---|
| One value, one or two simple updates | `useState` |
| Temporary form input | `useState` |
| Several kinds of change to the same data | `useReducer` |
| The next state depends on the previous state in non-trivial ways | `useReducer` |
| You want to test update rules without rendering | `useReducer` |
A reducer costs extra code: action types, a switch, and dispatch calls. For a list with only an add button, useState is simpler. This to-do app has four operations on one array, which is where a reducer starts to pay off.
Testing the reducer on its own
Because the reducer is pure, you can test it without React. Export it from its file, then call it like any function.
import { todosReducer } from "./todosReducer";
test("toggled flips only the matching item", () => {
const before = [
{ id: "a", title: "One", done: false },
{ id: "b", title: "Two", done: false },
];
const after = todosReducer(before, { type: "toggled", id: "a" });
expect(after[0].done).toBe(true);
expect(after[1]).toBe(before[1]);
expect(before[0].done).toBe(false);
});The last two assertions check immutability. The untouched item keeps the same reference, and the original array is not modified.
Common errors
- Mutating state in a case. Writing
todos.push(...)ortodo.done = !todo.donechanges the old state. Use spread,mapandfilter. - Impure ids in the reducer. Calling
crypto.randomUUID()inside theaddedcase gives different ids when React runs the reducer twice in development. Create the id at the dispatch site. - Forgetting to return. A
casethat computes a value but has noreturnfalls through to the next case. Always return in every branch. - Passing the wrong shape. Dispatching
{ type: "deleted", todoId }while the reducer readsaction.idproducesundefined, andfilterthen keeps every item. Keep action fields consistent. Some teams define a constant or helper for each action to avoid typos. - Calling the reducer yourself. Pass the function to
useReducerand calldispatch. Do not calltodosReducer(todos, action)in a handler and expect the screen to change.
Where this leads
With every update going through dispatch, later chapters get simpler. Persisting to localStorage can watch one todos value. Sharing state through context can pass dispatch down once, instead of threading three callbacks through every level.
Exercise
A teammate writes this case in the reducer and reports that clicking "Add" never updates the screen: case "added": todos.push({ id: action.id, title: action.title, done: false }); return todos;. Explain why, and write the fix.
Show answer
The case mutates the existing array with push and returns the same reference. React compares the returned value with the previous state by reference, sees no change, and skips the re-render. The fix is to return a new array: case "added": return [...todos, { id: action.id, title: action.title, done: false }];.
Exercise
Add a "cleared" action that removes every completed to-do. Write the reducer case and the dispatch call.
Show answer
Reducer case: case "cleared": return todos.filter((t) => !t.done);. Dispatch call: dispatch({ type: "cleared" }). The action needs no extra fields because the rule only depends on the current state.