How to use the useReducer React hook

By

Tagged: React

Learn how the useReducer React hook manages complex state by dispatching actions to a pure reducer function, a Redux style alternative to useState.

Since React introduced hooks, I worked with them on several projects and they are just great.

Removing all class-based components makes the code feel much more “real” JavaScript. And function components can finally manage state.

Check out my React hooks introduction first, if you’re new to them.

One hook I sometimes use is useReducer.

import { useReducer } from 'react'

Since the JSX transform that landed in React 17, you don’t need import React. Just import the hook. Same in React 19.

This hook is used to manage state. Sort of like useState, except more complex.

This is the key difference between useState and useReducer: with useReducer, state is altered by passing messages rather than calling the updater function.

If you know how Redux works, that’s basically the same. A reducer is a pure function that calculates the next state based on the previous state and the action that has been dispatched.

(currentState, action) => newState

What does “pure function” mean? A pure function takes an input and returns an output without changing the input or anything else. This means that a reducer returns a completely new state that substitutes the previous one.

A reducer should:

There is no reinforcement, but you should stick to the rules. And this has a nice benefit: reducers are much simpler to test, because they have no side effects.

This allows to centralize the state management, allowing components to modify it by sending messages, and also allows you to use (and alter) a more complex state in your components.

Let’s do an example, with a counter component.

useReducer accepts as arguments a reducer function, and an initial state value. It also takes an optional third argument, init. You call it as useReducer(reducer, initialArg, init). init is a function that computes the initial state from initialArg. Handy when that setup is expensive.

In this case our state is an integer, which starts from 0:

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, 0)
}

The reducer is a function that takes, as explained above, the current state and an action, which can be a value of any type you want. In this case it’s a string. In real code, actions are commonly objects like { type: 'increment' }. I keep the string here so the example stays small:

const reducer = (state, action) => {
  switch (action) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      throw new Error()
  }
}

We also make the component output some JSX to make this simple app work:

const Counter = () => {
  const [count, dispatch] = useReducer(reducer, 0)
  return (
    <>
      Counter: {count}
      <button onClick={() => dispatch('INCREMENT')}>+</button>
      <button onClick={() => dispatch('DECREMENT')}>-</button>
    </>
  )
}

Here is the full example on Codepen: https://codepen.io/flaviocopes/pen/MMQgrB/

A counter is small enough that useState would do. The hook pays off when state is an object and different actions change different fields.

Here the action is an object with a type, which is the usual shape:

const reducer = (state, action) => {
  switch (action.type) {
    case 'rename':
      return { ...state, name: action.name }
    case 'toggle':
      return { ...state, done: !state.done }
    default:
      throw new Error()
  }
}

const Task = () => {
  const [task, dispatch] = useReducer(reducer, {
    name: 'Write the post',
    done: false
  })

  return (
    <>
      <input
        value={task.name}
        onChange={(event) => {
          dispatch({ type: 'rename', name: event.target.value })
        }}
      />
      <button onClick={() => dispatch({ type: 'toggle' })}>
        {task.done ? 'Done' : 'Open'}
      </button>
    </>
  )
}

Each action returns a new object. We copy the previous state with ...state and change one field. We never edit state in place.

If the initial state needs a bit of work, pass a third argument. React calls that function with the second argument and uses the return value:

const [task, dispatch] = useReducer(
  reducer,
  'Write the post',
  (name) => ({ name, done: false })
)

My advice is to keep useState when you have one value, or a few values that do not depend on each other. Reach for useReducer when the next state depends on the previous one in more than one way, or several fields change together.

Want me to talk about your product? You can sponsor this site.

Related posts about react: