useReducer: State Logic in One Place

A cart whose changes all go through one reducer function. Dispatch actions and watch React run the reducer.

React · beginner · 8 min · 18 steps · free

What you'll learn

UseReducer.jsx

import { useReducer } from 'react';

function cartReducer(cart, action) {
  switch (action.type) {
    case 'added':
      return [...cart, action.item];
    case 'cleared':
      return [];
    default:
      throw new Error('Unknown action: ' + action.type);
  }
}

export default function Cart() {
  const [cart, dispatch] = useReducer(cartReducer, []);

  return (
    <div>
      <p>{cart.length} items: {cart.join(', ')}</p>
      <button onClick={() => dispatch({ type: 'added', item: 'Milk' })}>Add milk</button>
      <button onClick={() => dispatch({ type: 'cleared' })}>Clear</button>
    </div>
  );
}

Step by step

  1. React renders <Cart> for the first time: it calls the Cart function.
  2. useReducer stores the starting state, [], and gives back cart and dispatch.
  3. Cart returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  4. React turns the JSX into real page elements and shows them: look at the Screen panel.
  5. You click the “Add milk” button. React calls its onClick handler.
  6. dispatch({ type: "added", item: "Milk" }) sends an action. The reducer has not run yet.
  7. React renders Cart again, and runs the reducer with the current cart and the action.
  8. The "added" case matches: the reducer returns a new array, the old cart plus "Milk".
  9. useReducer returns the latest state: cart = ["Milk"].
  10. Cart returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  11. React compares the new JSX with the last one and updates only what changed on the page.
  12. You click the “Clear” button. React calls its onClick handler.
  13. dispatch({ type: 'cleared' }) sends an action. React will run the reducer with it on the next render.
  14. React renders <Cart> again (render 3): it calls Cart once more, from the top.
  15. "cleared" returns an empty array.
  16. useReducer returns the latest state: cart = [].
  17. Cart returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  18. The cart is empty again.

Common mistakes

Best practices

Key takeaways

Check yourself

Where does the update logic live?

Answer: In the reducer

Can a reducer change cart.push(x) and return cart?

Answer: No, return a new array

·

More in Sharing State