Skip to the code

A cart context around server-rendered pages

Leaf and Kettle's header shows how many teas are in the cart, and every tea in the list has an Add button. Both read the cart from React context, and context only works in Client Components. Write the provider, app/cart-provider.tsx, whose default export is CartProvider, and which also exports useCart.

CartProvider takes children, keeps the cart in state, and provides { items, count, add }. items has one { slug, quantity } for each tea added, in the order each was first added. count is the sum of the quantities. add(slug) adds one of that tea.

useCart() returns that value. Outside a CartProvider it throws an Error with the message useCart must be used inside a CartProvider, so a missing provider shows up at once instead of as a cart that never changes.

The shop's layout, app/(shop)/layout.tsx, is a Server Component, and it wraps the header and each page in the provider. The pages it gets as children, like the async tea list, stay Server Components: Next.js renders them on the server and passes their output through the provider.

Each CartProvider keeps a cart of its own. On the server, one copy of a module serves every visitor's request, so a cart kept in a variable outside the component would mix up customers' carts.

// app/(shop)/layout.tsx
<CartProvider>
  <header><CartCount /></header>
  <main>{children}</main>
</CartProvider>
 
Add Mint tea, Add Mint tea, Add Green tea
→ Cart (3), items: [{ slug: "mint", quantity: 2 }, { slug: "green", quantity: 1 }]

The app's other files

lib/teas.ts, read-only. Import it as @/lib/teas.

export type Tea = { slug: string; name: string };
 
const teas: Tea[] = [
  { slug: "green", name: "Green tea" },
  { slug: "mint", name: "Mint tea" },
  { slug: "oolong", name: "Oolong tea" },
];
 
/** Every tea, in the shop's order. */
export async function getTeas(): Promise<Tea[]> {
  return teas;
}

app/(shop)/layout.tsx, read-only. Import it as @/app/(shop)/layout.

import type { ReactNode } from "react";
import CartProvider from "../cart-provider";
import CartCount from "../components/cart-count";
 
export default function ShopLayout({ children }: { children: ReactNode }) {
  return (
    <CartProvider>
      <header>
        <CartCount />
      </header>
      <main>{children}</main>
    </CartProvider>
  );
}

app/(shop)/teas/page.tsx, read-only. Import it as @/app/(shop)/teas/page.

import { getTeas } from "@/lib/teas";
import AddToCart from "../../components/add-to-cart";
 
export default async function TeasPage() {
  const teas = await getTeas();
 
  return (
    <>
      <h1>Our teas</h1>
      <ul>
        {teas.map((tea) => (
          <li key={tea.slug}>
            {tea.name} <AddToCart slug={tea.slug} name={tea.name} />
          </li>
        ))}
      </ul>
    </>
  );
}

app/components/cart-count.tsx, read-only. Import it as @/app/components/cart-count.

"use client";
 
import { useCart } from "../cart-provider";
 
export default function CartCount() {
  const { count } = useCart();
  return <p>Cart ({count})</p>;
}

app/components/add-to-cart.tsx, read-only. Import it as @/app/components/add-to-cart.

"use client";
 
import { useCart } from "../cart-provider";
 
export default function AddToCart({ slug, name }: { slug: string; name: string }) {
  const { add } = useCart();
  return (
    <button type="button" onClick={() => add(slug)}>
      Add {name}
    </button>
  );
}

What the tests check

  1. is a Client Component around the shop's server-rendered pages
    const renderOnServer = async (element, options) => {
      try {
        return await renderServer(element, options);
      } catch (error) {
        if (/reading 'use[A-Za-z]*'/.test(String(error && error.message))) {
          throw new Error('A component that calls hooks ran as a Server Component, where there are none. Does its file start with "use client"? (' + error.message + ")");
        }
        throw error;
      }
    };
    await renderOnServer(
      <Layout>
        <Page />
      </Layout>,
    );
    expect(screen.getByRole("heading", { level: 1, name: "Our teas" })).toBeInTheDocument();
    expect(screen.getAllByRole("button").map((button) => button.textContent)).toEqual(["Add Green tea", "Add Mint tea", "Add Oolong tea"]);
    expect(screen.getByText("Cart (0)")).toBeInTheDocument();
    
  2. adding a tea updates the count in the header
    await renderServer(
      <Layout>
        <Page />
      </Layout>,
    );
    await user.click(screen.getByRole("button", { name: "Add Mint tea" }));
    expect(screen.getByText("Cart (1)")).toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "Add Mint tea" }));
    await user.click(screen.getByRole("button", { name: "Add Green tea" }));
    expect(screen.getByText("Cart (3)")).toBeInTheDocument();
    
  3. keeps one item per tea with its quantity, in the order first added
    const { result } = renderHook(() => useCart(), { wrapper: CartProvider });
    expect(result.current.items).toEqual([]);
    act(() => result.current.add("mint"));
    act(() => result.current.add("green"));
    act(() => result.current.add("mint"));
    expect(result.current.items).toEqual([
      { slug: "mint", quantity: 2 },
      { slug: "green", quantity: 1 },
    ]);
    expect(result.current.count).toBe(3);
    
  4. useCart outside a CartProvider throws a clear error
    expect(() => renderHook(() => useCart())).toThrow("useCart must be used inside a CartProvider");
    
  5. each provider keeps a cart of its own
    const first = renderHook(() => useCart(), { wrapper: CartProvider });
    const second = renderHook(() => useCart(), { wrapper: CartProvider });
    act(() => first.result.current.add("oolong"));
    act(() => first.result.current.add("oolong"));
    expect(first.result.current.count).toBe(2);
    expect(second.result.current.count).toBe(0);
    expect(second.result.current.items).toEqual([]);
    

Learn more

app/cart-provider.tsxSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).