useReducer for Complex State
When state has many parts that change together (a cart with add, remove and change quantity), useReducer keeps all the change rules in one place.
A reducer is a plain function: it takes the current state and an action (what happened), and returns the new state.
As state grows, update logic gets scattered across many event handlers: one adds to the cart, another removes, another changes quantity, each with its own setState calls. A reducer gathers all these rules in one function. Components just describe what happened ("ADD_ITEM") by dispatching an action, and the reducer decides how the state changes. This makes complex state easier to follow and to test.
Example
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.24.7/babel.min.js"></script>
<script type="text/babel">
const { useReducer } = React;
function cartReducer(cart, action) {
switch (action.type) {
case "add": {
const found = cart.find(i => i.name === action.name);
if (found) return cart.map(i => i.name === action.name ? { ...i, qty: i.qty + 1 } : i);
return [...cart, { name: action.name, price: action.price, qty: 1 }];
}
case "remove":
return cart.filter(i => i.name !== action.name);
case "clear":
return [];
default:
return cart;
}
}
function App() {
const [cart, dispatch] = useReducer(cartReducer, []);
const total = cart.reduce((s, i) => s + i.price * i.qty, 0);
return (
<div>
<button onClick={() => dispatch({ type: "add", name: "Tea", price: 120 })}>+ Tea</button>
<button onClick={() => dispatch({ type: "add", name: "Biscuits", price: 40 })}>+ Biscuits</button>
<button onClick={() => dispatch({ type: "clear" })}>Clear</button>
<ul>
{cart.map(i => (
<li key={i.name}>
{i.name} x {i.qty} = ₹{i.price * i.qty}{" "}
<button onClick={() => dispatch({ type: "remove", name: i.name })}>✕</button>
</li>
))}
</ul>
<b>Total: ₹{total}</b>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>▶ Try it yourselfuseState or useReducer?
- useState - a few simple values (a toggle, a text box).
- useReducer - many related values, or the next state depends on the previous one in several ways.
A reducer must be pure: no fetching, no timers, no changing the old state. Always return a new array or object.
Key points
- A reducer is a pure function: (state, action) => new state.
- Components dispatch actions instead of setting state directly.
- Use it for many related values; useState for simple ones.
📝 Test yourself
1. What does dispatch({ type: "clear" }) do?
2. Which of these is allowed inside a reducer?
3. Fill in the hook name:
const [cart, dispatch] = (cartReducer, []);
