React in Practice · 26 min · 210 XP

State transitions with useReducer

Move related state transitions into a pure reducer so every event has one explicit result.

Several state values that change together are easier to reason about as one state machine. useReducer(reducer, initialState) returns the current state and dispatch. An event dispatches a plain action; the reducer decides the next state.

jsx
function reducer(state, action) {
  if (action.type === "resolved") {
    return state.map((ticket) =>
      ticket.id === action.id ? { ...ticket, status: "resolved" } : ticket,
    );
  }
  return state;
}

const [tickets, dispatch] = useReducer(reducer, initialTickets);
dispatch({ type: "resolved", id: 42 });

Reducers must be pure: the same state and action produce the same result, with no requests, timers or mutation. That makes transitions testable without rendering. Event handlers may perform an external action and dispatch the result, but the reducer only calculates.

An unknown action should either throw during development or return the existing state unchanged. Returning a fresh copy for no change causes unnecessary renders and hides misspelled action names.

Loading your workspace…