LLearnCode
Academy/react/State that stays coherent

intermediate · 24 minute study

Name events; centralize transitions

When several controls change related state, a reducer makes the valid transitions visible in one place.

Loading progressEvidence grows with practice
Useful preparation · 1 prerequisite

Use this as a map, not a lock. If these ideas are familiar, continue.

First, build a mental model

A reducer is a pure function: nextState = reduce(currentState, event). The event describes what happened; the reducer decides its state consequences.

  1. Use event names that describe intent, not arbitrary property assignments.
  2. Return new objects for changed state.
  3. Keep requests, timers and storage outside the reducer.
  4. Derive totals/counts from canonical state instead of storing redundant copies.
Read the codejsx · educational example
function reducer(state, event) {
  switch (event.type) {
    case 'added': return { ...state, items: [...state.items, event.item] };
    case 'removed': return { ...state, items: state.items.filter(x => x.id !== event.id) };
    default: return state;
  }
}
function ItemList() {
  const [state, dispatch] = useReducer(reducer, { items: [] });
  const itemCount = state.items.length;
  return <p>{itemCount} items</p>;
}
  1. Event

    The UI reports added or removed with the required payload.

  2. Transition

    The reducer computes a new state without performing I/O.

  3. Derived UI

    The count always reflects the current item array.

Production thinking

Take this beyond the example.

Test reducers with event sequences and invariants. Keep account scope and asynchronous commit identity in explicit events when those boundaries matter.

Sources and further reading

Your evidence

unseen is a local learning signal, not a credential or proof of production competence.

Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.

Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.

Next lesson · Effects synchronize with something outside React →