React ยท Chapter 16 of 42

useReducer Hook

`useReducer` is an alternative to useState for managing more complex state logic, especially when state transitions depend on an action type.

It works like Redux: you dispatch actions to a reducer function, which returns the new state based on the current state and the action.

Reducer function

A reducer is a pure function: `(state, action) => newState`. It should never mutate state directly.

Dispatching actions

Call `dispatch({ type: 'increment' })` to trigger the reducer, which computes and returns the next state.

Example 1 (jsx)
import { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "increment": return { count: state.count + 1 };
    case "decrement": return { count: state.count - 1 };
    default: return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return (
    <button onClick={() => dispatch({ type: "increment" })}>
      Count: {state.count}
    </button>
  );
}
Output
Count: 0 (increments on click)

Dispatching an action runs the reducer to compute new state.

Key points

  • useReducer manages complex state logic with a reducer function.
  • Reducers are pure functions: (state, action) => newState.
  • dispatch() sends actions to trigger state transitions.
  • Useful when state logic involves multiple sub-values or complex updates.
๐Ÿ’ก Note: useReducer is often paired with useContext to build simple global state management.

๐Ÿ“ Quick Quiz

1. What does a reducer function return?

2. How do you trigger a state change with useReducer?

3. When is useReducer preferred over useState?