Sub topic 11
Moving update logic into a reducer
This chapter assumes you have a working to-do app with useState in App, and that you know map, filter, and spread syntax. Here you move the update logic out of the component and into a reducer.
Why a reducer
So far App has three handlers: add, toggle, and delete. Each one calls setTodos with its own logic, so the rules for changing the list are spread across the component. A reducer collects them in one function. Components then describe what happened, and the reducer decides how the list changes.
A reducer is a function that takes the current state and an action, and returns the next state. An action is a plain object that says what happened, usually with a type field.
Writing the reducer
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" });The reducer must be pure. Given the same state and action, it returns the same result, and it never mutates todos. Each case builds a new array, as in the immutable updates chapter. The default case throws, so a misspelled action type fails loudly instead of being ignored.
Generate the id in the event handler, not in the reducer. crypto.randomUUID() returns a different value on every call, and a reducer that calls it is no longer pure. React may run reducers twice in development to catch this kind of bug.
Wiring it into App
Replace useState for the list with useReducer. The handlers shrink to one dispatch call each.
import { useReducer, useState } from "react";
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("");
}
// render as before, with:
// onToggle={(id) => dispatch({ type: "toggled", id })}
// onDelete={(id) => dispatch({ type: "deleted", id })}
}The text field stays in useState. It is temporary form input, not part of the list's update rules, so it does not belong in the reducer.
How the data flows
Common errors
- Mutating state in a case. Calling
todos.push(...)or settingt.done = truecan leave React with the same reference, so the UI may not update. Return new arrays and objects. - Forgetting
return. A case that falls through or returns nothing sets the state toundefined, andtodos.mapthen crashes. - Calling the reducer yourself. Call
dispatch, nottodosReducer. React runs the reducer. - Impure work in the reducer. Random ids, dates, and
localStoragecalls belong in handlers or effects.
When to choose a reducer
Use useState when updates are simple and few. Switch to useReducer when several handlers change the same state in related ways, or when you want to test the update rules without rendering anything. Because the reducer is a plain function, you can call it directly in a test.
Exercise
Add a "cleared" action to todosReducer that removes all completed to-dos. What does the case look like, and how would a button dispatch it?
Show answer
Add case "cleared": return todos.filter((t) => !t.done); to the switch. The button calls dispatch({ type: "cleared" }) in its onClick, for example <button type="button" onClick={() => dispatch({ type: "cleared" })}>Clear completed</button>. The case returns a new array and needs no extra fields on the action.
Exercise
Why is id: crypto.randomUUID() placed in the dispatch call instead of inside the "added" case?
Show answer
A reducer must be pure, and crypto.randomUUID() returns a new value on every call. If React runs the reducer twice, as it can in development, the two runs would produce different results. Creating the id in the handler keeps the reducer deterministic.