The useReducer Hook
Managing complex state with reducers, actions, and the reducer pattern in React.
What you'll learn
- When to use useReducer instead of useState
- The reducer function and action objects
- Dispatching actions and the dispatch function
- Combining useReducer with useContext for global state
Concept
What Is useReducer?
useReducer is an alternative to useState for managing complex state logic. It follows the reducer pattern from Redux: state transitions are described by a pure reducer function that takes the current state and an action object, and returns the new state. You dispatch actions to trigger state changes. This pattern centralizes all state logic in one testable function and makes state transitions explicit and predictable.
When to Use useReducer
Use useReducer when you have state with multiple sub-values that are related, when the next state depends on the previous one in complex ways, or when you want to make state transitions more predictable and testable. If you find yourself writing many useState calls that are tightly coupled, or if your state update logic is spread across many handlers, useReducer can bring clarity. For simple independent values, useState is simpler.
The Reducer Function
A reducer is a pure function: (state, action) => newState. It typically uses a switch statement on action.type to determine which state transition to apply. Each case returns a new state object — never mutate the existing state. The action object carries a type string and optionally a payload with data needed for the transition. Reducers must be pure: no side effects, no API calls, no random values.
Dispatch and useContext
The useReducer hook returns [state, dispatch]. You call dispatch({ type: "INCREMENT" }) to trigger a state change. A powerful pattern is to combine useReducer with useContext: create a context that provides both the state and the dispatch function, so any component in the tree can read the state and dispatch actions without prop drilling. This is a lightweight alternative to Redux for medium-sized applications.
Action Type Conventions
A common convention is to use uppercase string constants for action types: "ADD_ITEM", "REMOVE_ITEM", "FETCH_SUCCESS". This makes them easy to grep for and distinguishes them from variables. In TypeScript, you can define a union type for actions to get exhaustive checking in the reducer's switch statement, ensuring every case is handled and the compiler catches missing cases.
Example
import { useReducer } from "react";
// Reducer function — pure, returns new state based on action.
function cartReducer(state, action) {
switch (action.type) {
case "ADD_ITEM":
return { ...state, items: [...state.items, action.item] };
case "REMOVE_ITEM":
return { items: state.items.filter(i => i.id !== action.id) };
case "CLEAR":
return { items: [] };
default:
return state;
}
}
function ShoppingCart() {
const [state, dispatch] = useReducer(cartReducer, { items: [] });
const addItem = (item) => dispatch({ type: "ADD_ITEM", item });
const removeItem = (id) => dispatch({ type: "REMOVE_ITEM", id });
return (
<div>
<h2>Cart ({state.items.length} items)</h2>
<button onClick={() => addItem({ id: Date.now(), name: "Product" })}>Add</button>
<button onClick={() => dispatch({ type: "CLEAR" })}>Clear</button>
<ul>
{state.items.map(item => (
<li key={item.id}>
{item.name}
<button onClick={() => removeItem(item.id)}>Remove</button>
</li>
))}
</ul>
</div>
);
}
The reducer handles ADD_ITEM, REMOVE_ITEM, and CLEAR actions. Each returns a new state object. Components dispatch actions instead of calling setters directly.
Try it
- JSON Formatter
Reducer state and action objects are JSON — format to inspect transitions.
- Code Diff
Compare reducer logic when adding new action types.
Common mistakes
The mistake
Mutating state inside the reducer instead of returning a new object
The fix
Reducers must be pure. Always return a new state object: { ...state, items: [...state.items, newItem] }. Never push to the existing array or modify state directly.
The mistake
Putting side effects like API calls inside the reducer
The fix
Reducers must be pure functions with no side effects. Do API calls in event handlers or useEffect, then dispatch an action with the result. The reducer only updates state.
Practice The useReducer Hook
6 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.