0Pricing
Frontend Academy · Lesson

useReducer for Complex State

Model state transitions with a reducer function, dispatch action objects, and prefer useReducer over useState when state logic grows complex.

When useState Isn't Enough

When state transitions involve complex logic, multiple related values, or conditions where the new state depends on the previous state in non-trivial ways, useReducer is a cleaner choice than multiple useState calls.

Reducer Function Pattern

A reducer is a pure function: (state, action) => newState. It takes the current state and an action object, and returns the next state. No mutations — always return a new object.

type Action =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'reset'; payload: number };

function counterReducer(state: number, action: Action): number {
  switch (action.type) {
    case 'increment': return state + 1;
    case 'decrement': return state - 1;
    case 'reset':     return action.payload;
    default: return state;
  }
}

All lessons in this course

  1. useContext for Global State
  2. useReducer for Complex State
  3. useMemo and useCallback for Performance
  4. Custom Hooks: Extracting Reusable Logic
← Back to Frontend Academy