useReducer — React

useReducer gathers all the rules for changing a state into one function, the reducer. useReducer(reducer, initialState) takes two arguments, the reducer…

When a piece of state can change in many ways (add, subtract, change the step, reset), the rules for changing it are easily scattered over many handlers. useReducer gathers all of those rules into one function called a reducer. Imagine a small restaurant. You don't walk into the kitchen and change the order yourself. You write a slip, say "add one", and give it to the cook. The cook reads the slip, checks the current order, then writes the new order following the rule book. The slip is the action, giving it to the cook is dispatch, the cook's rule book is the reducer, and the current order is the state.

Three parts: state, action, reducer

The reducer: the rule book

Here is the reducer for a counter that has a count (the number) and a step (the size of each step):

const initialState = { count: 0, step: 1 }

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { ...state, count: state.count + state.step }
    case "decrement":
      return { ...state, count: state.count - state.step }
    case "setStep":
      return { ...state, step: action.step }
    case "reset":
      return initialState
    default:
      return state
  }
}

A reducer has to be pure: it only calculates the new state from the old state and the action. A reducer must not fetch, set timers, or change the old state object.

Using it in a component: useReducer and dispatch

This Counter component uses the reducer above:

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <div>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <span>{state.count}</span>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <input
        type="range"
        min="1"
        max="5"
        value={state.step}
        onChange={(e) => dispatch({ type: "setStep", step: Number(e.target.value) })}
      />
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
    </div>
  )
}

This is what the Lab's console records when you send these actions one by one, in this order:

Action sent State before State after Shown
{ type: "increment" } { count: 0, step: 1 } { count: 1, step: 1 } 1
{ type: "increment" } { count: 1, step: 1 } { count: 2, step: 1 } 2
{ type: "setStep", step: 5 } { count: 2, step: 1 } { count: 2, step: 5 } 2
{ type: "increment" } { count: 2, step: 5 } { count: 7, step: 5 } 7
{ type: "incremnt" } { count: 7, step: 5 } { count: 7, step: 5 }, the same 7
{ type: "reset" } { count: 7, step: 5 } { count: 0, step: 1 } 0

When to use useReducer instead of useState

⚠️ Reducers that quietly break the state

TL;DR: useReducer gathers all the rules for changing a state into one function, the reducer. useReducer(reducer, initialState) takes two arguments, the reducer function and the starting state, and returns [state, dispatch]. A component sends actions (objects that say what happened) with dispatch({ type: "increment" }), and an action can carry data ({ type: "setStep", step: 5 }). The reducer is a function (state, action) => newState that picks the rule with a switch (action.type). It has to be pure: it only calculates, with no side effects. Every case returns a new object ({ ...state, count: ... }), and default: return state makes a mistyped action change nothing. Use useReducer for complex state with many kinds of action. For simple values, useState is enough.

⚡ The reducer: the rule book

Write:

const initialState = { count: 0, step: 1 }

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { ...state, count: state.count + state.step }
    case "reset":
      return initialState
    default:
      return state
  }
}

Meaning: A reducer is a function that takes the current state and an action (an object that says what happened, for example { type: "increment" }). The reducer then returns a new state. switch (action.type) picks the rule, and ...state copies the parts that don't change. An unknown action goes to default, and the state is returned as it is.

⚡ useReducer and dispatch

Write:

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <div>
      <span>{state.count}</span>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </div>
  )
}
Guess first: useReducer takes two arguments. What are they?

The reducer function and the starting state. It returns [state, dispatch].

Meaning: The component doesn't change the state itself. The component only sends actions through dispatch, then the reducer calculates the new state, and React renders again.

⚡ When to use useReducer

Meaning: useState for a value that stands on its own with simple changes. useReducer for complex state with many kinds of action, or several values that change together, such as a shopping cart (add, remove, change the amount, empty it).

What you will learn