Reducer Patterns
Last updated: 2026-11-02
Reducer Patterns Reducer Patterns
A few idiomatic patterns keep reducers tidy: lazy initialization through the third argument, immutable updates of object and array state, computing derived values while rendering instead of storing them, and resetting a whole state tree with a reset action or a changed key. Mastering these keeps even a complex state machine clean. The shared principle is that the reducer stays a pure function, while everything impure — network calls, timers, storage — happens in the event handlers or effects around it.
| Group | Effects & Performance |
|---|---|
| Kind | Pattern |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
// lazy initialization: the initial state is computed from an argument
const [state, dispatch] = useReducer(reducer, props, init)
// reset the whole state tree
case 'reset': return init(props)
// the immutable update templates for arrays
[...state, item] // add
state.filter(i => i.id !== id) // remove
state.map(i => i.id === id ? { ...i, done: true } : i) // edit
Returns:No return value; this entry describes an encoding pattern rather than a function.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
"Next" accumulates the trail, "Back" steps back one and "Reset" returns to the start at once — the example demonstrates lazy initialization and the reset pattern.