← Learning Hub
Advanced

Project: Shopping Cart App

Let's combine everything: components, props, state, a reducer, context, effects and localStorage, into a small shop with a cart that survives a refresh.

This project uses every main React idea together: components and props for the UI, a reducer for cart rules, context so any component can reach the cart, an effect to save it, and localStorage so it survives a refresh. It's the same structure used by real shopping apps, just smaller. Read the code piece by piece and notice how each part has one clear job.

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 { createContext, useContext, useReducer, useEffect } = React;

      const PRODUCTS = [
        { id: 1, name: "Cotton T-shirt", price: 499 },
        { id: 2, name: "Denim jeans", price: 1299 },
        { id: 3, name: "Running shoes", price: 2499 },
      ];

      function reducer(cart, a) {
        switch (a.type) {
          case "add":    return { ...cart, [a.id]: (cart[a.id] || 0) + 1 };
          case "minus": {
            const n = (cart[a.id] || 0) - 1;
            const copy = { ...cart };
            if (n <= 0) delete copy[a.id]; else copy[a.id] = n;
            return copy;
          }
          case "clear":  return {};
          default:       return cart;
        }
      }

      const CartContext = createContext(null);

      function CartProvider({ children }) {
        const [cart, dispatch] = useReducer(reducer, {}, () => {
          try { return JSON.parse(localStorage.getItem("cart")) || {}; } catch { return {}; }
        });
        useEffect(() => {
          try { localStorage.setItem("cart", JSON.stringify(cart)); } catch {}
        }, [cart]);
        return <CartContext.Provider value={{ cart, dispatch }}>{children}</CartContext.Provider>;
      }
      const useCart = () => useContext(CartContext);

      function ProductCard({ p }) {
        const { dispatch } = useCart();
        return (
          <div style={{ border: "1px solid #ddd", borderRadius: 10, padding: 12 }}>
            <b>{p.name}</b>
            <p>₹{p.price}</p>
            <button onClick={() => dispatch({ type: "add", id: p.id })}>Add to cart</button>
          </div>
        );
      }

      function Cart() {
        const { cart, dispatch } = useCart();
        const lines = PRODUCTS.filter(p => cart[p.id]);
        const total = lines.reduce((s, p) => s + p.price * cart[p.id], 0);
        if (!lines.length) return <p>Your cart is empty.</p>;
        return (
          <div>
            {lines.map(p => (
              <div key={p.id}>
                {p.name}{" "}
                <button onClick={() => dispatch({ type: "minus", id: p.id })}>−</button>
                {" "}{cart[p.id]}{" "}
                <button onClick={() => dispatch({ type: "add", id: p.id })}>+</button>
                {" "}= ₹{p.price * cart[p.id]}
              </div>
            ))}
            <h3>Total: ₹{total.toLocaleString("en-IN")}</h3>
            <button onClick={() => dispatch({ type: "clear" })}>Empty cart</button>
          </div>
        );
      }

      function App() {
        return (
          <CartProvider>
            <h2>Terixto Mini Shop</h2>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12 }}>
              {PRODUCTS.map(p => <ProductCard key={p.id} p={p} />)}
            </div>
            <h2>Cart</h2>
            <Cart />
          </CartProvider>
        );
      }

      ReactDOM.createRoot(document.getElementById("root")).render(<App />);
    </script>
  </body>
</html>
▶ Try it yourself

Challenges

  • Show the number of items in a header badge using useCart().
  • Load the products from an API with useEffect and a loading message.
  • Add React Router pages: / for products and /cart for the cart.
  • Build it as a real project with Vite (see the beginner lesson "Create a Real React App").
The third argument of useReducer is an "init" function. It runs once, so reading localStorage happens only when the app starts.

📝 Test yourself

1. Why does the cart survive a page refresh?
2. What does useCart() return here?
3. Which hook holds the cart's change rules?