ReactEasy

What is a Reducer?

A reducer is a pure function (state, action) => newState that decides how state changes in response to an action. It must not mutate its arguments, call APIs, generate random values or have other side effects; it only computes and returns the next state. Reducers are used by Redux and by React's useReducer.

Rules

  1. Pure: same state and action always give the same result.
  2. Immutable updates: return new objects and arrays instead of modifying existing ones (Redux Toolkit uses Immer, so "mutating" code in createSlice is safe because Immer produces a new copy).
  3. No side effects: no fetching, logging to servers, timers or Date.now() inside. Put those in thunks, listeners, effects or event handlers, and pass values in the action payload.
  4. Return the existing state for actions it does not handle.

Why pure functions

  • Predictable and easy to unit test: call it with inputs and check the output.
  • Enable time-travel debugging and replaying actions.
  • Safe with React's Strict Mode, which calls useReducer reducers twice in development.

Organizing reducers

  • One reducer per feature slice, combined at the store level.
  • Handle actions as events ("todo/added") rather than setters.
  • Derive values with selectors instead of storing duplicated data.

Testing example

expect(cartReducer(initial, added({ id: "pen" }))).toEqual({...}), with no store or component needed.

Code example

tsx
1type Todo = { id: string; text: string; done: boolean };
2type Action =
3 | { type: "todo/added"; id: string; text: string }
4 | { type: "todo/toggled"; id: string }
5 | { type: "todo/cleared_done" };
6
7// Pure: no Date.now(), no random ids, no fetch. Ids come in the action payload.
8export function todosReducer(state: Todo[] = [], action: Action): Todo[] {
9 switch (action.type) {
10 case "todo/added":
11 return [...state, { id: action.id, text: action.text, done: false }];
12 case "todo/toggled":
13 return state.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
14 case "todo/cleared_done":
15 return state.filter((t) => !t.done);
16 default:
17 return state;
18 }
19}
20
21// Easy to test without React
22const s1 = todosReducer([], { type: "todo/added", id: "1", text: "Write tests" });
23const s2 = todosReducer(s1, { type: "todo/toggled", id: "1" });
24console.log(s2[0].done, s1[0].done); // true false (s1 untouched)

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app