In this lab, we’ll build a small shop with React to see how context works. The project is Cart Shopping Context.
Here’s an overview of what we’ll cover:
Project Setup: we’ll create a new React project with Vite.
Context API: we’ll create a CartContext, wrap the tree in a CartProvider that owns the state, and read or update that state from components in two different branches.
A custom hook: a small useCart hook keeps the consumers tidy.
No prop drilling: Product and CartBadge share the cart count without passing props through Header, Main, or ProductList.
By the end of this lab, you’ll have a working shop where Add to cart in the main column updates the badge in the header, and you’ll know why that works.
Tree diagram: App mounts CartProvider, which provides CartContext to two branches. Header contains CartBadge; Main contains ProductList and CartSummary.
CartContext is created once at module level. It is not a component. CartProvider owns the state — a count held in useState(0) — and exposes { count, setCount } through the provider.
Main and ProductList also pass through: no cart props. Each Product calls setCount when you click Add to cart. CartSummary reads the count and can clear it.
The entry file stays the Vite default: createRoot and StrictMode in src/main.jsx.
5 What to notice
Product and CartBadge are in different branches with no common props. Clicking Add to cart updates the header badge.
Without context, you’d lift count into App and pass it down through Main, ProductList, Header, and so on (prop drilling).
Every consumer re-renders when the context value changes. That’s fine here, but it’s why big apps split contexts (for example a separate CartContext and ThemeContext).
The playground in the margin (and the interactive demo) is only an illustration of that idea. The lab code itself has two products, Keyboard and Mouse.