The cart is needed in many places: the header counts its items, the cart page lists them, the products page adds to it. Kept in one component's state, it would have to travel down as props through components that don't use it, like Layout. Context lets any component inside a provider read a value directly.
It has three pieces. createContext makes the context. A Provider wraps part of the app and gives it a value. useContext reads that value in any component inside. For example, a theme:
export const ThemeContext = createContext("light");
<ThemeContext.Provider value="dark">
<Layout />
</ThemeContext.Provider>
// in any component inside Layout:
const theme = useContext(ThemeContext); // "dark"
When the provider's state changes, every component that reads the context draws again. One setCart in the provider, and the header's count changes on every page.
The given App.jsx wraps the routes in CartProvider, and Header, CartPage and ProductsPage already call useContext(CartContext). The check adds a Mug and a Teapot, then opens the cart:
> open /?category=kitchen
link: Cart (0) -> /cart
> click "Add to cart" in "Mug"
request: POST /api/cart {"product_id": 1, "quantity": 1} -> 201
+ link: Cart (1) -> /cart
> click "Add to cart" in "Teapot"
request: POST /api/cart {"product_id": 6, "quantity": 1} -> 201
+ link: Cart (2) -> /cart
> click "Cart (2)"
item: Mug × 1 $12
item: Teapot × 1 $22
text: Total: $34
> reload the page
link: Cart (2) -> /cart (current)
Your task: in src/CartContext.jsx, export CartContext, write add(product) that sends the product to the cart API and puts the new cart in state, and make CartProvider return a CartContext.Provider with { cart, add } around its children.
Assignment
Follow the Coding Tutorial to share one cart with every page through a context, so the header's count changes the moment a product is added.
Hintvalue={{ cart, add }} has two pairs of braces: the outer ones are JSX, the inner ones make an object. addToCart answers with the whole cart, so its answer goes straight into setCart.
Free plan: 30 tutor messages. PRO is unlimited.
