Skip to content

Shopping Cart with Context

Medium ~40 min

What you'll build

A product listing with an add-to-cart button and a cart display showing items, quantities, and total. Cart state is shared via Context so any component can access it.

Goals

  • Create a Context for cart state
  • Build a Provider with cart logic
  • Consume context in multiple components
  • Implement add, remove, and quantity update

Prerequisites

  • useContext and Context API
  • useState
  • List rendering

Steps

  1. 1

    Create the Cart Context and Provider

    Define a CartContext and a Provider component that holds cart state and exposes add/remove functions.

    Code
    const CartContext = createContext();
    
    function CartProvider({ children }) {
      const [cart, setCart] = useState([]);
      const addToCart = (item) => {
        setCart(prev => {
          const existing = prev.find(i => i.id === item.id);
          if (existing) return prev.map(i => i.id === item.id ? { ...i, qty: i.qty + 1 } : i);
          return [...prev, { ...item, qty: 1 }];
        });
      };
      return <CartContext.Provider value={{ cart, addToCart }}>{children}</CartContext.Provider>;
    }

    Expected result

    Cart context is set up with add functionality.

  2. 2

    Create product and cart components

    ProductList shows products with add buttons. Cart displays items from context and the total.

    Code
    function ProductList({ products }) {
      const { addToCart } = useContext(CartContext);
      return products.map(p => (
        <div key={p.id}>{p.name} - ${p.price}
          <button onClick={() => addToCart(p)}>Add</button>
        </div>
      ));
    }
    
    function Cart() {
      const { cart } = useContext(CartContext);
      return (
        <div>
          {cart.map(item => <div key={item.id}>{item.name} x{item.qty}</div>)}
          <h3>Total: ${cart.reduce((s, i) => s + i.price * i.qty, 0)}</h3>
        </div>
      );
    }

    Expected result

    Products can be added to cart, cart shows items and total.

  3. 3

    Wrap the app in the Provider

    Wrap your app in CartProvider so all components can access the cart context.

    Code
    <CartProvider>
      <ProductList products={products} />
      <Cart />
    </CartProvider>

    Expected result

    The app works with shared cart state via Context.

  4. 4

    Add state management & event handling

    Use useState to manage component state and add onClick/onChange handlers to interactive elements. State is the heart of React components, and event handling lets them respond to user actions.

    Code
    import { useState } from "react";
    
    export function MyComponent() {
      const [count, setCount] = useState(0);
      const [text, setText] = useState("");
    
      return (
        <div>
          <button onClick={() => setCount(c => c + 1)}>
            Count: {count}
          </button>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
        </div>
      );
    }

    Expected result

    Clicking the button increments the count; the input content updates in real time as you type.

  5. 5

    Add Props validation & component split

    Define a Props interface (TypeScript) or propTypes for the component, and split large components into smaller sub-components. Type-safe Props make the component interface clear and reusable.

    Code
    interface ChildProps {
      label: string;
      value: number;
      onChange: (v: number) => void;
    }
    
    function Child({ label, value, onChange }: ChildProps) {
      return (
        <label>
          {label}
          <input
            type="number"
            value={value}
            onChange={(e) => onChange(Number(e.target.value))}
          />
        </label>
      );
    }

    Expected result

    The child component receives type-safe Props; the parent can reuse it to render multiple fields.

Try it yourself

What you learned

You learned to use Context for shared state across components without prop drilling. The Provider holds the state and exposes actions; consumers read and update the cart from anywhere in the tree.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic