useReducer
In one line
useReducer is a Hook that manages state using a reducer function (like Redux) — ideal for complex state logic with multiple sub-values.
In simple words
useReducer is an alternative to useState for managing complex state. Instead of calling a setter with a new value, you dispatch actions, and a reducer function decides how to update the state based on the action type.
The pattern is: const [state, dispatch] = useReducer(reducer, initialState). The reducer is a pure function (state, action) => newState. You call dispatch({ type: 'increment' }) and the reducer handles it.
useReducer is preferable when: state has multiple related sub-values, the next state depends on the previous in complex ways, or you want to centralize and test your state logic. It is the same pattern used by Redux, making it a natural stepping stone to Redux.
Example
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" })}>{state.count}</button>;
}The reducer handles 'increment' and 'decrement' actions. The component dispatches actions instead of calling a setter directly.
Related terms
Related Resources
Related Lessons
- useReducer
Learn useReducer for complex state management.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.