useCart throws a missing-provider error.
Likely cause: A consumer is rendered outside the provider subtree.
Check and correct: Ensure the shared layout wraps both navigation and page children.
PROJECT 3 · LESSON 8 OF 18
Connect product buttons, the header count and the cart page.
Continue from lesson 7: Build a cart on one page. Keep existing files; create or replace the complete files listed below.
Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.
Now Add to Cart lives on a product card, the count lives in the header, and the details live on another page. Three independent arrays would disagree. We need one owner for state and a way for multiple descendants to read it.
The cart now has three consumers: product cards, a navigation badge and the cart page. Move state into a provider above all three instead of maintaining separate arrays.
A Server Component can render a Client Component provider and pass server-rendered children into it. The root layout can remain a Server Component.
The root layout wraps the navigation and routed content in CartProvider. The provider owns lines and passes a value containing the current lines and operations. CartLink, AddToCart and the cart page consume that value through useCart.
Context distributes access to state; it does not replace the state mechanism. useState still owns the array. The provider exposes small operations such as add, setQuantity and clear instead of making each button reproduce the update algorithm.
createContext starts with null because there is no meaningful cart outside a provider. useCart reads the nearest provider’s value. If that value is absent, it throws a useful configuration error instead of letting a distant component fail on an undefined property.
Every consumer sees the cart from its nearest provider. Placing a new provider inside each page creates new independent carts. Putting one in a shared layout lets those routes use the same mounted provider during ordinary internal navigation.
The layout remains a Server Component and renders the Client Component provider. It passes children into the provider rather than asking the provider module to import every server page. This lets the server prepare the route content while the client provider handles browser state.
The context value includes functions, but those functions are created and consumed within the client component tree. This is different from trying to serialize a normal server callback as a prop to a client component. ProductCard can remain a server component and render a small AddToCart client control with just a product ID.
CartLink sums quantities, not lines.length. Two notebooks in one line represent two items. Keep that distinction consistent with what the badge tells the shopper.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
The shared layout mounts one CartProvider.
An AddToCart consumer calls its add operation with a product ID.
The provider updates its lines state and supplies a new context value.
The header count and cart view read the same new state, including after internal navigation.
The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
This is the single owner of shared client cart state and its permitted operations.
"use client";
import { createContext, useContext, useState, type ReactNode } from "react";
import { changeQuantity, type CartLine } from "@/lib/cart";
type Cart = {
lines: CartLine[];
setQuantity: (id: string, quantity: number) => void;
add: (id: string) => void;
clear: () => void;
};
const Context = createContext<Cart | null>(null);
export function CartProvider({ children }: { children: ReactNode }) {
const [lines, setLines] = useState<CartLine[]>([]);
function setQuantity(id: string, quantity: number) {
setLines((old) => changeQuantity(old, id, quantity));
}
function add(id: string) {
setLines((old) =>
changeQuantity(
old,
id,
(old.find((l) => l.productId === id)?.quantity ?? 0) + 1,
),
);
}
return (
<Context.Provider
value={{ lines, setQuantity, add, clear: () => setLines([]) }}
>
{children}
</Context.Provider>
);
}
export function useCart() {
const cart = useContext(Context);
if (!cart) throw new Error("Wrap this component in CartProvider");
return cart;
}
This displays a live navigation badge using the same cart as the product controls and cart page.
"use client";
import Link from "next/link";
import { useCart } from "./cart-provider";
export default function CartLink() {
const { lines } = useCart();
return (
<Link href="/cart">
Cart ({lines.reduce((sum, line) => sum + line.quantity, 0)})
</Link>
);
}
This gives a product card a small client-side control without moving the whole catalog into client state.
"use client";
import { useCart } from "./cart-provider";
export default function AddToCart({ id }: { id: string }) {
const { add } = useCart();
return <button onClick={() => add(id)}>Add to cart</button>;
}
This keeps one cart provider above all of the store’s consumers.
import type { ReactNode } from "react";
import Link from "next/link";
import { CartProvider } from "@/components/cart-provider";
import CartLink from "@/components/cart-link";
import "./globals.css";
export const metadata = {
title: "EduShop",
description: "My Next.js learning project",
};
export default function Layout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<CartProvider>
<nav>
<Link href="/">Home</Link>
<Link href="/products">Products</Link>
<CartLink />
<Link href="/about">About</Link>
</nav>
<main>{children}</main>
</CartProvider>
</body>
</html>
);
}
This renders one product without owning catalog loading or filtering.
import Link from "next/link";
import type { Product } from "@/lib/products";
import { money } from "@/lib/money";
import AddToCart from "./add-to-cart";
export default function ProductCard({ product }: { product: Product }) {
return (
<article>
<h2>
<Link href={`/products/${product.slug}`}>{product.name}</Link>
</h2>
<p>{product.description}</p>
<strong>{money(product.price)}</strong>
<p>
<AddToCart id={product.id} />
</p>
</article>
);
}
This renders cart choices and derives their display values from the catalog.
"use client";
import { products } from "@/lib/products";
import { money } from "@/lib/money";
import { useCart } from "@/components/cart-provider";
export default function CartPage() {
const { lines, setQuantity, clear } = useCart();
const total = lines.reduce(
(sum, line) =>
sum +
(products.find((p) => p.id === line.productId)?.price ?? 0) *
line.quantity,
0,
);
return (
<>
<h1>Your cart</h1>
{lines.map((line) => {
const product = products.find((p) => p.id === line.productId);
return (
<article key={line.productId}>
<h2>{product?.name ?? "Unavailable product"}</h2>
<label>
Quantity{" "}
<input
type="number"
min="1"
max="10"
value={line.quantity}
onChange={(e) => {
const n = Number(e.target.value);
if (Number.isInteger(n) && n > 0)
setQuantity(line.productId, n);
}}
/>
</label>
<p>{money((product?.price ?? 0) * line.quantity)}</p>
<button onClick={() => setQuantity(line.productId, 0)}>
Remove
</button>
</article>
);
})}
{!lines.length && (
<p>Your cart is empty. Visit Products to add an item.</p>
)}
<p>Total: {money(total)}</p>
{!!lines.length && <button onClick={clear}>Clear cart</button>}
</>
);
}
Temporarily wrap only the Products page in a new CartProvider. Compare its button with the header badge, then remove the extra provider.
The inner product button can update a different cart while the header stays unchanged.
Context resolves to the nearest provider. An extra provider changes ownership and does not merge its state with the outer provider.
Putting a provider inside each page creates separate carts. Place one provider in their shared layout.
Likely cause: A consumer is rendered outside the provider subtree.
Check and correct: Ensure the shared layout wraps both navigation and page children.
Likely cause: You may be forcing a full reload or mounting a new provider per page.
Check and correct: Use internal Link navigation and one provider in the common layout. Refresh persistence comes next.
Add AddToCart to the individual product page.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
No. It shares in-memory React state with descendants. Persistence is a separate feature.
All consumers follow the same rules, such as one line per product and a quantity cap, without duplicating those rules.