CodeBlanks Logo Icon CodeBlanks

What is useReducer?

Learn to move state updates into a function with useReducer.

What is useReducer?

useReducer is an alternative to useState for complex state logic. It manages state with a reducer function: (state, action) => newState.

useReducer takes the current state and an action and returns the new state. You send actions with dispatch; the reducer does the rest.

When many related fields or complex transitions exist, useReducer is cleaner than useState.

Reducer structure

A reducer is a pure function: function reducer(state, action). Inside you usually switch(action.type) and return a new state per action type.

A reducer must have no side effects; the same input always gives the same output. This makes it testable.

The new state is always a fresh object; the old state is never mutated.

Practice Reducer skeleton

Complete the skeleton. Define a function reducer taking (state, action); its body does return state;. Then write a Counter component; import useReducer and define const [state, dispatch] = useReducer(reducer, 0);. Return <p>{state}</p>. Export it.

Starter code

App.jsx
import { useReducer } from "react";

// Define reducer and Counter here

Sample solution

App.jsx
import { useReducer } from "react";

function reducer(state, action) { return state; }

function Counter() {
  const [state, dispatch] = useReducer(reducer, 0);
  return <p>{state}</p>;
}

export default Counter;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is useReducer preferred?

App.jsx
For a simple value useState is enough.
  • Never
  • Only for number counters
  • For complex state logic Correct answer
  • Only for fetch

Explanation: It is clean for complex transitions and related fields.

2 What is useReducer: fill in the missing part

Question
const [state, dispatch] = useReducer(____, initial);
Answer
const [state, dispatch] = useReducer(reducer, initial);

Explanation: useReducer takes the reducer function.

3 What is useReducer: match the terms

Term Meaning
reducer Pure function
dispatch Sends an action
action Event info
state Current state

All lessons in Beginner