Home / Learn React / useReducer: Complex State

useReducer: Complex State

When state has many related pieces and many ways to change, put the update logic in a reducer function: given the old state and an action, return the new state.

In shortconst [state, dispatch] = useReducer(reducer, initial). Components call dispatch({ type: "add" }). The reducer decides the new state.

Theory in plain words

The reducer cycleUI eventdispatch({ type, ... })reducer(state, action)returns new stateReact renderswith new state
The reducer cycle

What it is

A reducer is a pure function (state, action) => newState. useReducer keeps the state and gives you dispatch to send actions to the reducer.

Why we use it

When many event handlers each change the same state in slightly different ways, the logic is scattered. A reducer puts every possible change in one place, which is easy to read, test and debug.

How it works

You call dispatch(action). React calls your reducer with the current state and that action, takes the returned value as the new state and renders. Never mutate state inside the reducer.

Where it is used

  • Todo lists, carts and wizards with many actions
  • Forms with many related fields
  • Together with Context for app wide state
  • State machines (loading, success, error)

A cart with a reducer

useReducerTry it Yourself
useStateuseReducer
Best forSimple, independent valuesMany related values and many kinds of changes
Update logicInside event handlersIn one reducer function
TestingTest the componentTest the reducer alone, it is a pure function
Code sizeLess at firstMore at first, less as it grows
Careful:Reducers must be pure: no fetch, no random values, no mutation of the old state. Put side effects in handlers or effects.

Quick quiz

1. What does a reducer return?

2. What does dispatch do?

3. When is useReducer better than useState?

Common questions

What does a reducer return?

The new state. (state, action) returns the new state.

What does dispatch do?

Sends an action to the reducer. React then calls the reducer with it.

When is useReducer better than useState?

For many related values and many kinds of updates. It centralizes update logic.