Skip to main content

Search

Search problems, hooks, and pages

Shopping Cart

Build a product listing page with a shopping cart. Products can be added to the cart, their quantities adjusted, and removed. The cart persists across page refreshes using localStorage.

Requirements

  • Display a grid of products (id, name, price, category)
  • Add to Cart button on each product
  • Cart sidebar/panel shows added items with quantity controls (+ / −)
  • Remove individual items from the cart
  • Show subtotal per item (price × quantity) and grand total
  • Cart badge on the cart button shows total item count
  • Persist cart to localStorage via a custom useLocalStorage hook
  • Clear cart button empties the cart

Key Patterns

useLocalStorage<T>(key, initial) hookcart: CartItem[] (productId + quantity)Derived totals via Array.reduce()Add: find-or-append patternQuantity update: map()Remove: filter()

Important

Interview Tip

Never store product data in the cart — only store { productId, quantity }. Look up product details from the products array when rendering. This keeps cart state minimal. For totals: cartTotal = cart.reduce((sum, item) => sum + item.quantity * getProduct(item.productId).price, 0).
Store

React Masterclass

Course

49

TypeScript Pro

Course

39

Node.js Handbook

Book

29

CSS Art Kit

Design

19

Docker Deep Dive

Course

34

System Design Guide

Book

59