Every component that reads the cart needs useContext and the CartContext object. A custom hook hides both. It is a function whose name starts with use and which calls other hooks. Components call useCart() and get what they need. Only src/CartContext.jsx ever touches the context.
Here is the same idea for a theme:
const ThemeContext = createContext(null);
export function useTheme() {
return useContext(ThemeContext);
}
Outside every provider, useContext returns the context's default, here null. The component then crashes later, with a confusing TypeError somewhere else. A good hook checks for null and throws an Error with a clear message instead.
The provider also hands out the cart already opened: { items, total, add, remove }. remove sends DELETE /api/cart/<id> and keeps the cart the API answers with. The check must print:
> open /?category=kitchen
link: Cart (0) -> /cart
item: Mug $12
item: Teapot $22
> click "Add to cart" in "Mug", then in "Teapot"
link: Cart (2) -> /cart
> click "Cart (2)", then "Remove" in "Mug"
request: DELETE /api/cart/1 -> 200
text: Total: $22
> a component outside CartProvider calls useCart()
it throws Error: useCart must be used inside CartProvider
Your task: in src/CartContext.jsx, write remove, the value object and the provider's return. Then export useCart(): it returns the value, and throws "useCart must be used inside CartProvider" when there is no provider.
Assignment
Follow the Coding Tutorial to finish CartProvider and write the useCart hook that Header, ProductsPage and CartPage already import.
Hintremove works like add, with removeFromCart. useCart has three parts: read useContext(CartContext), throw if it is null, return it.
Free plan: 30 tutor messages. PRO is unlimited.
