← Back to React, page 1

react-0010 · Medium mid

What is the difference between useState and useReducer, and when would you switch from one to the other?

useState stores a value and gives a setter. useReducer stores state and a dispatch function: you send an action describing what happened, and a pure reducer function returns the next state. Both trigger re-renders the same way. Prefer useState for independent values and useReducer when state has several related fields, many transitions, or rules that should live in one tested place.

Full answer

useState is the simplest tool. const [count, setCount] = useState(0) and you set a new value directly. It works well for a toggle, an input value or a counter.

useReducer moves the update rules out of the event handlers. You write a reducer, a function (state, action) => newState, and the component calls dispatch({ type: 'added', item }). The handler says what happened. The reducer decides how state changes.

Switch to useReducer when state is an object whose fields change together, when the next state depends on the previous one in several different ways, or when the same update is triggered from many places. Examples are a shopping cart, a multi-step form or a game board. The logic is gathered in one function that is easy to read and easy to unit test, because it is a pure function with no React inside.

The reducer must be pure: no fetching, no random values, no mutation. Return a new object or array instead of changing the old one. React may call it more than once in development, and it relies on the previous state staying unchanged.

Other facts to know. dispatch has a stable identity, so passing it to children or effects does not cause extra renders. A reducer and context together are a common light replacement for a state library in a small app. useReducer also accepts a third argument, an init function, to compute expensive starting state once.

useReducer is not automatically better. For a few unrelated values, several useState calls are shorter and clearer.

The code below keeps a canteen bill. The total is calculated from the items during render, so it never goes out of sync.

jsx
import { useReducer } from 'react';

const initialState = { nextId: 1, items: [] };

function billReducer(state, action) {
  switch (action.type) {
    case 'added':
      return {
        nextId: state.nextId + 1,
        items: [...state.items, { id: state.nextId, name: action.name, price: action.price }],
      };
    case 'removed':
      return { ...state, items: state.items.filter((item) => item.id !== action.id) };
    case 'cleared':
      return initialState;
    default:
      throw new Error('Unknown action: ' + action.type);
  }
}

export default function CanteenBill() {
  const [state, dispatch] = useReducer(billReducer, initialState);
  const total = state.items.reduce((sum, item) => sum + item.price, 0);

  return (
    <div>
      <button onClick={() => dispatch({ type: 'added', name: 'samosa', price: 15 })}>Add samosa</button>
      <button onClick={() => dispatch({ type: 'added', name: 'tea', price: 10 })}>Add tea</button>
      <button onClick={() => dispatch({ type: 'cleared' })}>Clear</button>
      <ul>
        {state.items.map((item) => (
          <li key={item.id}>
            {item.name} {item.price}
            <button onClick={() => dispatch({ type: 'removed', id: item.id })}>Remove {item.name}</button>
          </li>
        ))}
      </ul>
      <p>Total: {total}</p>
    </div>
  );
}

The check added a samosa, a tea and another samosa, then removed the tea. Total after those steps (15 + 15 = 30): <div><button>Add samosa</button><button>Add tea</button><button>Clear</button><ul><li>samosa 15<button>Remove samosa</button></li><li>samosa 15<button>Remove samosa</button></li></ul><p>Total: 30</p></div>

Key points

  • useState sets values directly. useReducer sends actions to a pure reducer that returns the next state.
  • Use useReducer for related fields, many transitions or logic you want to test on its own.
  • The reducer must not mutate state or cause side effects.
  • dispatch is stable between renders, which makes it safe to pass down.
  • Derive values such as totals during render instead of storing them in state.

Common mistakes

  • Mutating state inside the reducer, for example calling state.items.push(item).
  • Putting API calls or random values inside a reducer.
  • Storing a derived value such as the total in state and forgetting to update it in one branch.
  • Switching to useReducer for a single boolean, which adds code without benefit.
  • Not handling unknown action types, which hides typos.

Follow-ups

  • How would you combine useReducer with context for a small app, and what are the re-render costs?
  • Why does React call a reducer twice in StrictMode development, and what does that tell you?
  • When would you move from useReducer to Zustand or Redux Toolkit?

Tips

  • Frame the answer around "where does the update logic live". That is the real difference.
  • Use an example with several transitions (a cart) instead of a counter, which makes useReducer look pointless.
  • Mention purity and testing. Interviewers listen for them.