useReducer(reducer, initialArg, init?) moves update logic out of event handlers into one pure function, (state, action) => nextState. Handlers say what happened, dispatch({ type: 'submitted' }); the reducer decides how the state changes. Everything else works as with useState: each render sees a snapshot, dispatches are queued and batched, an unchanged result (by Object.is) skips the children, and dispatch keeps the same identity across renders.
Reach for a reducer when:
- Several values change together. A form's status, error and data move as one: one action updates them consistently, where three setters can leave them disagreeing.
- The next state depends on other state. An updater function only sees its own variable; a reducer sees the whole state object.
- Many handlers make similar updates. One function is easier to read, log ("which action caused this?") and unit-test without rendering anything.
- The updater must travel far.
dispatchis stable, so it can go through context once and every consumer can send actions without new callbacks each render.
Stay with useState for independent, simple values such as a toggle, an input or a counter. The two mix freely in one component, and converting between them is mechanical: useState is a reducer whose actions are values or updater functions.
The rules come from where reducers run, which is during rendering:
- Keep them pure: no requests, timeouts or mutation. Strict Mode calls them twice in development.
- Return a new object for a change and the same
statefor a no-op. - Throw on unknown actions instead of falling through to
undefined. - Name actions after interactions (
reset_form), not field assignments (fiveset_fields).