useReducer
Manage complex state with clear, predictable update logic — the foundation of Redux-style state.
What you will learn
- Use useReducer for structured state
- Write a reducer function
- Dispatch actions
State logic in one place
When state updates get complex, useReducer centralises the logic in a reducer — a function that takes the current state and an action, and returns the next state.
function reducer(state, action) {
switch (action.type) {
case "inc": return { count: state.count + 1 };
case "dec": return { count: state.count - 1 };
case "reset": return { count: 0 };
default: return state;
}
}
function App() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<h2>Count: {state.count}</h2>
<button onClick={() => dispatch({ type: "inc" })}>+</button>
<button onClick={() => dispatch({ type: "dec" })}>-</button>
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
);
}Here is the cycle each time you click a button:
- A button dispatches an action — a small object describing what happened, e.g.
dispatch({ type: "inc" }). - React calls the
reducerwith the currentstateand thataction. - The
reducer’sswitchmatchesaction.typeand returns the next state —"inc"returnscount + 1,"dec"returnscount - 1,"reset"returns0, anything else returns the state unchanged. - React re-renders with the new state, so the count on screen updates.
The win is that all the update rules live in one place (the reducer), instead of being scattered across many setState calls. That keeps complex state predictable.
Note: Output: Count: 0 with +, - and Reset buttons. + makes it 1, 2, 3…; - goes back down; Reset returns it to 0.
Note: You dispatch an action ({ type: "inc" }), and the reducer decides the next state. This pattern scales well and is the heart of Redux, a popular state library.
Q. In useReducer, what does dispatch do?
✍️ Practice
- Build a counter using
useReducerwith inc/dec/reset actions. - Add a “set to 10” action.
🏠 Homework
- Build a simple to-do reducer with add and remove actions.