Hooks & State — Intermediate React challenge.
Manage a shopping cart's state with useReducer instead of useState. Multiple related actions — adding, adjusting quantity, removing, clearing — each need different update logic, which is exactly the kind of complexity useReducer is built for.
Requirements
- cartReducer.js exports initialState ({ items: [] }) and a pure cartReducer(state, action) function.
- ADD_ITEM increments quantity if the item already exists, otherwise adds it with quantity: 1.
- UPDATE_QUANTITY sets the item's quantity; a quantity of 0 or below removes the item.
- REMOVE_ITEM removes the matching item; CLEAR_CART resets items to an empty array.
- An unrecognized action.type throws an Error rather than silently returning unchanged state.
- Cart.js wires the reducer up with useReducer, renders catalog Add buttons, a per-item +/-/Remove row, a Clear Cart button, and a formatted total price.
- An empty cart renders a friendly empty-state message instead of an empty list.
Signature
function cartReducer(state: { items: CartItem[] }, action: CartAction): { items: CartItem[] }
function Cart(): JSX.ElementExample
cartReducer({ items: [] }, { type: "ADD_ITEM", payload: { id: 1, name: "Keyboard", price: 50 } })
// ⇒ { items: [{ id: 1, name: "Keyboard", price: 50, quantity: 1 }] }Constraints
- cartReducer must be a pure function — no side effects, no mutation of the incoming state object.
- Do not use useState for cart data — useReducer must own the cart's state.