Part 10 / Topic 4 of 8
useReducer's signature
const [state, dispatch] = useReducer(reducer, initialState) is the hook form of everything Sections 2-3 just built in plain JavaScript. examples/03_usereducer_wiring.jsx's CartWithReducer wires cartReducer in and never computes a next state itself - every button just describes what happened:
// examples/03_usereducer_wiring.jsx
export function CartWithReducer() {
const [cart, dispatch] = useReducer(cartReducer, initialCart);
const total = cart.items.reduce((sum, item) => sum + item.price * item.quantity, 0);
return (
<div>
<button onClick={() => dispatch({ type: "add", dish: PANEER_BUTTER_MASALA })}>Add Paneer Butter Masala</button>
<button onClick={() => dispatch({ type: "clear" })}>Clear cart</button>
{/* ... */}
</div>
);
}
dispatch never takes a new state - only an action. React hands that action, together with the current cart, to cartReducer, and re-renders with whatever it returns. Clicking "Add Paneer Butter Masala" twice really shows "Paneer Butter Masala x2" and "Total: ₹440"; clicking "Clear cart" afterward really empties the list and resets the total to "Total: ₹0" (examples/03_usereducer_wiring.test.jsx) - the exact same cartReducer from Section 2, unchanged, now driving a real component. Notice total itself is a plain variable, computed fresh every render from cart.items - the derive-don't-duplicate rule from Part 6, still true inside a reducer-driven component.
Done here? The practice set for Part 10 — including the solutions — is on the part page.