intermediate

useReducer

Centralize complex state transitions with events, reducers, and explicit initialization.

`useReducer` pairs state with a dispatch function and a pure reducer `(state, action) => nextState`. It shines when many event types update related fields, when next state depends on previous in complex ways, or when you want testable transition tables.

You can pass a third initializer argument for lazy setup. Context plus `useReducer` can replace prop drilling for medium-sized local domains. It is not automatically faster than `useState` — the win is clarity of events.

					function reducer(state, action) {
  switch (action.type) {
    case "inc": return { count: state.count + 1 };
    default: return state;
  }
}
				

On interviews, explain the concept with a concrete example and name the behavior interviewers probe.

Common pitfalls include hiding data flow, over-splitting components, and putting side effects in render.

The trade-off is often clarity versus reuse or explicit props versus convenience.

Checklist:

  • Model actions as explicit events.
  • Keep reducers pure and synchronous.
  • Colocate reducer with the owning component or hook.