React › Hooks

What is the useReducer hook and when is it a better choice than useState?

Intermediate

Answer

useReducer manages state using a function called a reducer, which decides how the state should change based on an action you send it. It becomes a better choice than useState when a component has several related pieces of state that often change together, or when the logic for updating state grows complicated.
function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'reset': return { count: 0 };
    default: return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return <button onClick={() => dispatch({ type: 'increment' })}>{state.count}</button>;
}
Real-world example A shopping cart with many related pieces of state, like items, quantity, and discounts, switches from several separate useState calls to a single useReducer, making all the related update logic live in one clear place.

Common follow-ups: How do you decide between using useState and useReducer for a specific component?;Can useReducer be combined with the Context API to share state widely?