R
Rishtaara
React: The Complete Guide
Lesson 20 of 28Article16 min

useReducer Hook

useReducer is like useState for complex state logic. You pass a reducer function and initial state. Dispatch actions instead of calling many setters.

useReducer — state with actions

useReducer is like useState for complex state logic. You pass a reducer function and initial state. Dispatch actions instead of calling many setters.

Real-life example: useReducer is a bank teller window — you hand a slip (action); the teller (reducer) updates the ledger (state) by fixed rules.

Counter with useReducer
import { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "reset":
      return { count: 0 };
    default:
      return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>{state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
    </div>
  );
}

When to prefer useReducer

Use when next state depends on many fields, or when multiple sub-components dispatch the same actions (often with Context).

Real-life example: useReducer is a traffic light controller — same rules every time; you only send "green" or "red" commands.

  • Todo apps with add, toggle, delete, filter
  • Multi-step forms with back/next validation
  • Combined with useContext for global reducer stores