Skip to lesson content

PROJECT 3 · LESSON 8 OF 18

Share the cart across routes

Connect product buttons, the header count and the cart page.

  • Context
  • provider placement
  • client islands

Your workspace: edushop

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.

1. Understand the problem and the concepts

Why we need this feature

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.

Lift ownership to the shared ancestor

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.

Read the custom hook and its guard

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.

Understand the server/client composition

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.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The shared layout mounts one CartProvider.

  2. An AddToCart consumer calls its add operation with a product ID.

  3. The provider updates its lines state and supplies a new context value.

  4. The header count and cart view read the same new state, including after internal navigation.

Why one array fixes three screens

  1. From /products, add one notebook. AddToCart does not own a separate notebook count.
  2. CartProvider changes its shared array to one p1 line with quantity 1.
  3. CartLink reduces that array and displays Cart (1).
  4. Opening /cart through Link shows the same p1 line because its consumer reads the same provider.

3. Build it, one file at a time

  1. Add CartProvider, CartLink and AddToCart. Replace the layout, product card and cart page.
  2. Add a product from /products and navigate to /cart.
  3. The layout persists through client navigation, so the provider keeps the same state.

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.

components/cart-provider.tsx

This is the single owner of shared client cart state and its permitted operations.

components/cart-provider.tsx
"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;
}

Read the code

  1. Context starts with null. CartProvider supplies lines and update functions to its descendants; useCart throws a useful error if that provider is missing.
  2. add uses the existing quantity from a functional update. setQuantity delegates the pure array transformation. clear requests a new empty array.
  3. The provider is mounted in the shared layout so internal route transitions can reuse the same state. Context itself does not persist data.

components/cart-link.tsx

This displays a live navigation badge using the same cart as the product controls and cart page.

components/cart-link.tsx
"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>
  );
}

Read the code

  1. useCart reads the nearest provider. The component does not keep a second cart count in state.
  2. reduce sums quantities starting from zero: two units in one line display 2, not 1.
  3. Link performs internal navigation to /cart so the common layout’s provider can remain mounted.

components/add-to-cart.tsx

This gives a product card a small client-side control without moving the whole catalog into client state.

components/add-to-cart.tsx
"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>;
}

Read the code

  1. The id prop is a plain product identifier passed by the parent. The component gets the add operation from useCart.
  2. The click handler calls add only when the user activates the button. Passing add(id) directly as the handler value would call it during rendering instead.
  3. In the persistence version, ready disables the button until stored cart data has been restored.

app/layout.tsx

This keeps one cart provider above all of the store’s consumers.

app/layout.tsx
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>
  );
}

Read the code

  1. The root layout remains a Server Component and wraps navigation and children in CartProvider.
  2. CartLink consumes shared state, while ordinary Links navigate between routes. The provider owns the interactive state; the layout still owns the document.
  3. Passing children through a client provider does not require importing all server page modules into that client module. Preserve this composition boundary.

components/product-card.tsx

This renders one product without owning catalog loading or filtering.

components/product-card.tsx
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>
  );
}

Read the code

  1. import type brings in the Product contract without importing runtime data. The product prop supplies the actual record.
  2. The Link uses the product slug to construct its details URL. money formats its integer price.
  3. The parent gives each repeated card a key. The key is used by React for sibling identity and is not automatically available as a normal card prop.
  4. AddToCart receives only the product ID. That small client component owns the browser click while the surrounding card remains reusable server presentation.

app/cart/page.tsx

This renders cart choices and derives their display values from the catalog.

app/cart/page.tsx
"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>}
    </>
  );
}

Read the code

  1. useCart replaces page-local state with the shared provider. The page, product buttons and header read the same lines.
  2. Each line looks up its product by ID and multiplies its unit price by quantity. reduce adds those line amounts into the displayed total.
  3. Quantity and remove controls request a new array rather than mutating existing state. Missing products have a fallback label; checkout later rejects unavailable choices.

4. Run it and check your result

  • The header count and cart quantities agree.
  • Using internal links preserves the cart. Refresh still resets it until the next lesson.

5. Predict, change and observe

Temporarily wrap only the Products page in a new CartProvider. Compare its button with the header badge, then remove the extra provider.

Compare your prediction with the expected result

What you should observe

The inner product button can update a different cart while the header stays unchanged.

Why it happens

Context resolves to the nearest provider. An extra provider changes ownership and does not merge its state with the outer provider.

6. Troubleshoot with evidence

A common mistake

Putting a provider inside each page creates separate carts. Place one provider in their shared layout.

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.

The cart resets when navigating.

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.

7. Practice and explain it back

Your independent task

Add AddToCart to the individual product page.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Does Context save the cart to a database?

No. It shares in-memory React state with descendants. Persistence is a separate feature.

Why keep update logic inside the provider?

All consumers follow the same rules, such as one line per product and a quantity cap, without duplicating those rules.