Skip to content

Lesson 8 of 9 · 22m

State Updates, Reducers, and Event-Like Thinking

Model application state as transitions, use reducers where they fit, and know when event sourcing ideas help versus when they become ceremony.

Once data is immutable, application behavior becomes a sequence of transitions: current state plus intent produces next state. That is the reducer pattern, and it appears in Redux, useReducer, undo systems, and synchronization protocols because it makes change inspectable. Use it where it clarifies behavior, not as paperwork for every click.

A reducer is a transition table

function cartReducer(state, action) {
  switch (action.type) {
    case "item_added":
      return { ...state, items: upsertById(state.items, action.item) };
    case "item_removed":
      return { ...state, items: state.items.filter((x) => x.id !== action.id) };
    default:
      return state;
  }
}

Every valid change is visible in one place. When debugging means asking "how could this state happen?", you inspect actions instead of grepping arbitrary assignments.

Actions describe intent, not setters

{ type: "set_items", items }                         // weak: setter in disguise
{ type: "promo_applied", code: "WINTER10", at: 1766534400000 } // intent

Meaningful actions can drive totals, validation, analytics, and audit logs. Setter-shaped actions throw away the reason and leave future readers to reverse-engineer it.

Reducers stay pure

Do not fetch, write storage, mutate, or generate timestamps inside a reducer. If time or randomness affects the result, pass it in with the action. Persist the next state in the shell. This is the same pure-core/impure-edge split from earlier, applied to state.

Borrow event logging without buying ceremony

state = reducer(state, action);
history.push({ action, at: action.at ?? Date.now() });
persist(state);

An append-only log of meaningful actions pays off in undo, audit trails, synchronization, and production debugging. Full event sourcing — rebuilding state by replaying every event — is usually unnecessary. Record domain events, not mousemove noise.

Normalized state beats deep trees

const state = {
  usersById: { u1: { id: "u1", name: "Ada" } },
  postsById: { p1: { id: "p1", authorId: "u1" } },
  postOrder: ["p1"],
};

Normalization makes immutable updates local. Deep nesting turns every update into copy ceremony and invites inconsistent duplicates.

Field notes

  • A reducer is overkill for one boolean toggle. Use it when transitions interact or ordering matters.
  • Do not store derived values; compute selectors from facts.
  • Time-travel debugging works only when actions are serializable and deterministic.
  • If one case does four unrelated things, the action is too coarse or the state shape is wrong.

Was this lesson helpful?

Sign in to rate