Skip to content
Tutorials Center
My learning

Topics

Lesson 103 of 132 ยท Projects

Project: Shopping Cart

Build a shopping cart in React with a cart reducer, context, quantity controls, coupon codes and currency totals formatted with Intl. Five runnable stages with derived state.

A shopping cart looks simple until you write one. Quantities must not go below one or above the stock. Prices must add up exactly. The header badge, the product list and the cart panel all need the same data, yet they sit in different parts of the page. And money has its own rules: floating-point numbers and currency formatting both bite.

This project walks through those problems in five stages, each a complete program. You will combine reducers, context, derived state and the browser's Intl.NumberFormat, and apply the guidance from context patterns on splitting state and dispatch.

Plan: what is state, what is derived

Start with the data model, because it decides everything else.

Products are a fixed catalog: id, name, price, stock. In a real app they would come from a server; here they are a constant array.

Money is stored as integer cents. 1999 means $19.99. Adding prices as decimals gives errors such as 0.1 + 0.2 = 0.30000000000000004; integers add exactly. Only the very last step, display, turns cents into a formatted string.

The cart stores only ids and quantities, like { tee: 2, mug: 1 }. It does not copy product names or prices. If it did, a price change in the catalog would leave stale copies in carts. Names, prices and line totals are looked up from the catalog during render.

Thing State or derived?
Quantity per product id State (in the cart reducer)
Coupon code the user typed State
Line totals, subtotal, discount, shipping, tax, total Derived
Number of items in the badge Derived
Whether "Add" is disabled (stock reached) Derived

Stage 1: a cart with useState

First the naive version. Products on screen, a cart in state, one "Add" button per product.

Stage 1: add to cart

It works, but already shows cracks: nothing stops quantity from passing the stock, there is no way to remove, and the price shows as raw cents. We need rules for the cart, and rules call for a reducer.

Stage 2: the cart reducer

The cart has several operations with real rules:

  • added: increase by one, but never beyond stock.
  • decremented: decrease by one; when it reaches zero, remove the entry (a quantity of 0 should not linger in the object).
  • removed: delete the entry.
  • cleared: empty the cart.

Put them in one pure function and test them before building any UI:

Stage 2: the reducer, tested without UI

Look at the third poster: stock is 2, so the third added returns the same object and the log marks it (unchanged). Returning the identical reference is how a reducer tells React "nothing happened", so no re-render is needed. Also look at decremented on a quantity of 1: the key disappears instead of becoming 0. Keeping the invariant "an entry exists only if the quantity is at least 1" makes every later calculation simpler (the count of line items is just Object.keys(items).length).

Reducers are a good place for business rules like stock limits, because every path to the state goes through them. A button that forgets to check stock cannot break the rule.

Stage 3: share the cart with context

The cart is needed in three places that are far apart in the tree: the header badge, the product cards and the cart panel. Passing items and dispatch as props through every layer is prop drilling. Context solves it: a CartProvider owns the reducer and publishes its value; any component below can read it with a hook.

Two details are worth the effort:

  1. Split state and dispatch into two contexts. dispatch never changes identity, so components that only send actions (like a "Remove" button) do not re-render when the cart changes.
  2. Wrap the contexts in custom hooks (useCart, useCartDispatch) that throw a clear error if used outside the provider.
Stage 3: CartProvider and hooks

CartBadge, ProductCard and CartPanel never receive the cart as a prop, yet they stay in sync. Add two posters: the product card's button becomes "Max in cart" for the poster, because soldOut is derived from the cart and the stock.

Note the React 19 syntax: <CartContext value={items}> is the provider itself; the old .Provider suffix is not needed (context).

Context re-renders every consumer when its value changes. For a cart that is fine. For a large, frequently changing state, split it into smaller contexts, select slices with an external store (external stores), or memoize the expensive consumers.

Stage 4: money and totals

Totals are pure arithmetic over the cart, so they belong in a plain function, not in state. We also need display formatting, and the browser provides it: Intl.NumberFormat formats currency correctly for a locale, with the right symbol, grouping and decimals.

The rules for our shop:

  • Coupon SAVE10: 10 % off the subtotal.
  • Shipping: $4.99, free when the discounted subtotal reaches $50.00 (and nothing is charged for an empty cart).
  • Tax: 8 % of the discounted subtotal.
  • Round to whole cents at each step with Math.round, so the lines shown always add up to the total shown.
Stage 4: totals and Intl formatting

Check the arithmetic by hand for the third scenario: the subtotal is 3 x 19.99 + 12.50 = $72.47; 10 % off removes $7.25 (rounded from 7.247), leaving $65.22, which is over $50, so shipping is free; 8 % tax on $65.22 is $5.22 (rounded from 5.2176); the total is $70.44. The empty cart correctly shows $0.00 everywhere instead of charging shipping.

Two design notes. First, the percentage rules are data (COUPONS, constants), so a new coupon is a new entry, not new code. Second, because calculateTotals is pure, it is trivial to test and safe to call on every render. There is no need for useMemo here: it loops over a handful of lines. Measure before memoizing (useMemo and useCallback).

Stage 5: the complete cart

Now assemble everything: the context from stage 3, the totals from stage 4, plus the finishing touches.

  • Quantity controls with minus and plus buttons whose labels name the product ("Increase T-shirt quantity"), disabled at the limits.
  • Coupon field. The text the user types is state (coupon in the cart state); whether it is valid is derived by looking it up. The input shows a message either way.
  • A summary listing subtotal, discount, shipping, tax and total.
  • Checkout. A simulated order button clears the cart and shows a confirmation. In a real app this is where you would send the cart to a server, and you would recalculate prices on the server rather than trusting the client.
  • Free-shipping hint. "Add $X more for free shipping" is another derived value.

Because the coupon is now part of the reducer state, state becomes an object { items, coupon }.

Stage 5: the complete shopping cart

Try this sequence: add three T-shirts and a mug, then type save10 in lowercase. The reducer upper-cases the text, so the coupon is accepted, a discount line appears, and the total drops from $78.27 to $70.44. Click "+" on the poster until it is disabled at two. Place the order and watch the cart clear.

What to notice

  • The state is tiny. { items: { tee: 3, mug: 1 }, coupon: 'SAVE10' }. Everything on screen (lines, totals, counts, hints, disabled buttons) is derived from it plus the constant catalog.
  • Rules live in one place. Stock limits are in the reducer, and money rules are in calculateTotals. UI components only display values and send actions.
  • Single source for numbers. Header, Summary and the checkout all call the same function, so they cannot disagree about the total.
  • Locale-aware output. Changing the formatter to new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }) would show 19,99 โ‚ฌ with no other change.
  • Accessibility. Controls have names that include the product, the status messages are live regions, and the coupon input has a visible label.

Never trust a client-side total. A visitor can change anything running in their browser. A real checkout must recompute prices, stock and discounts on the server from the ids and quantities alone, which is another reason to keep the cart state so small.

Ideas to extend it

  1. Persistence. Save state to storage in an effect and restore it with the reducer's init function, as in the todo project.
  2. Variants. Add sizes: the cart key becomes productId:size.
  3. Currency switch. Store the chosen currency in context and format with Intl.NumberFormat.
  4. Optimistic server sync. Send changes to an API and use useOptimistic.
  5. Tests. Test cartReducer and calculateTotals directly; they need no React (testing hooks and logic).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the cart store only product ids and quantities?

    Copying product data into the cart creates duplicates that can disagree with the catalog. Ids and quantities are the minimal state; the rest is looked up while rendering.
  2. 2. Why are prices kept as integer cents?

    Binary floating point cannot represent many decimal fractions exactly. Integer cents add exactly and are converted to a formatted currency string only for display.
  3. 3. What does returning the same state object from a reducer (as 'added' does at the stock limit) accomplish?

    React bails out when the next state is identical (Object.is) to the current one. Returning the unchanged reference is the idiomatic way to ignore an action.
  4. 4. Why split CartContext and CartDispatchContext?

    dispatch keeps the same identity across renders. Consumers of the dispatch context are not notified when the state context value changes.
  5. 5. Why must a real shop recalculate the total on the server?

    Anything running in the browser is under the visitor's control. The server should compute prices, discounts and stock from ids and quantities, then charge that amount.

Summary

  • Model the data first: a fixed catalog, a cart of { id: quantity }, money in integer cents, and everything else derived.
  • Put business rules (stock limits, removing zero quantities) in a pure reducer and test it without UI.
  • Share the cart with context; split state and dispatch contexts and wrap them in hooks that fail clearly outside the provider.
  • Compute totals in a pure function and format them with Intl.NumberFormat only at display time.
  • Derive hints, counts and disabled states instead of storing them; accept that checkout totals must be re-verified on a server.
  • Give controls descriptive accessible names and announce status messages with live regions.

Next: Project: Kanban Board