Part 06 / Stage 2
Client Components and the boundary
Goal: Learn exactly how to opt a component into the browser — the
"use client"directive — and the three rules that come with it: where the boundary should actually sit, what survives crossing it as a prop, and how a Server Component's own markup can still end up inside a Client Component without ever being imported by it. Built as a real, working mini-cart: an add-to-cart counter with its own quantity state, live inside an otherwise fully server-rendered product page. Time: ~6 h · Level: 🟢 finished Part 5, comfortable with why a Server Component can't holduseState
What you will learn
- The
"use client"directive: what it actually marks (a module boundary, not "this one component"), and where it propagates to - Where the boundary should go — the leaf component that needs interactivity, not the page around it
- What survives being passed from a Server Component to a Client Component as a prop, and what categorically does not (a function, proven as a real error)
- The composition pattern that lets a Client Component still show server-rendered content: passing it as
children, never as an import - A real, reproducible build error for the single most common boundary mistake: marking an entire page
"use client"when it didn't need to be - How to confirm exactly how much client-side JavaScript a Client Component island actually added, using the same chunk-diffing technique Part 5 introduced
Topics in this part
Practice
Every exercise adds files under harness/app/store/ (or a sibling scratch folder), runs a real command against them, and then removes what it added, restoring the harness to the exact state Part 6's README ends on. Copy the exact commands you ran and their real output into your own notes; do not type output from memory.
Exercise 1: A second leaf Client Component
Scenario: Apna Bazaar wants a "favorite this product" star next to the quick-add page, independent of the quantity counter.
What to do: Create app/store/_components/FavoriteToggle.tsx, a "use client" component taking one serializable prop (productId: string) and a useState<boolean> for whether it's favorited, rendering a <button> that toggles it. Compose it into a scratch page. Run next build and confirm the starting (unfavorited) state renders correctly in the HTML. Delete everything afterward.
Sample output (run for real against this course's harness):
$ npm run build
...
├ ○ /store/ex1-favorite
...
$ grep -o '<button[^>]*>.*</button>' .next/server/app/store/ex1-favorite.html
<button type="button" aria-pressed="false">☆ favorite<!-- --> (<!-- -->p1<!-- -->)</button>
💡 Hint: This is exactly AddToCartCounter's shape, just with one boolean instead of a number — a leaf Client Component, serializable props, nothing else.
Exercise 2: Trigger and revert the event-handler-prop error, on your own component
Scenario: You want the exact error in your own notes, from your own files.
What to do: Take the FavoriteToggle from Exercise 1 and add an onToggled: () => void prop to it. Pass a function defined in the Server Component page as that prop. Run next build and capture the real error. Then remove the prop and confirm the build is green again.
Sample output (run for real against this course's harness, using the same mechanism as the README's section 3):
$ npm run build
...
Error: Event handlers cannot be passed to Client Component props.
{productId: "p1", onToggled: function onToggled}
^^^^^^^^^^^^^^^^^^
If you need interactivity, consider converting part of this to a Client Component.
💡 Hint: The fix the error names — "consider converting part of this to a Client Component" — is already true here: FavoriteToggle should call its own setFavorited directly, never ask its server parent for a callback.
Exercise 3: Trigger and revert the "use client" + generateStaticParams error, on a different route
Scenario: Section 4 reproduced this on QuickAddPage. Confirm it's a general rule, not specific to that one file.
What to do: Pick any other dynamic page in the harness that exports generateStaticParams (/store/products/[id] or /store/go/[id]) and add "use client" to the very top of it, temporarily. Run next build and capture the real error. Revert immediately.
Sample output (run for real against this course's harness, on /store/go/[id]):
$ npm run build
...
Error: Turbopack build failed with 1 error:
./app/store/(shop)/go/[id]/page.tsx:1:1
Error: Next.js can't recognize the exported `generateStaticParams` field in route. App pages cannot use both "use client" and export function "generateStaticParams()".
...
(The exact file and line will match whichever route you picked — the error message's shape stays the same.)
💡 Hint: This route also calls redirect(), a Server-Component-only function (Part 3) — so this one page would actually break for two independent reasons if it were a Client Component, not just the one generateStaticParams reports first.
Exercise 4: The children-slot pattern, with a different pair of components
Scenario: Prove the composition pattern from section 5 generalizes beyond ExpandablePanel/ProductSpecs.
What to do: Build a "use client" Tabs component that takes labelA, labelB (strings) and panelA, panelB (React.ReactNode) as props, with a useState tracking which tab is active, rendering only the active panel. Build a plain Server Component, SupplierCard, that renders a supplier's name and city. Compose <Tabs labelA="Details" labelB="Supplier" panelA={<ProductSpecs product={product} />} panelB={<SupplierCard .../>} /> from a page. Build, then grep the raw HTML for text from the inactive tab's content, and confirm it's present in the payload even though it isn't the one showing.
Sample output (run for real against this course's harness, panelB being the inactive tab since Tabs defaults to "a"):
$ npm run build
$ grep -o 'Jaipur Blue Pottery Co-op' .next/server/app/store/ex4-tabs.html
Jaipur Blue Pottery Co-op
The raw payload around that match shows exactly why it's there even though the tab isn't showing:
"panelB":["$","p",null,{"children":["Jaipur Blue Pottery Co-op",", ","Jaipur"]}]
💡 Hint: This is section 5's exact proof technique (grep the raw HTML for a value from the server-rendered children, even though it isn't currently displayed) — reused on content you built yourself. Watch out for one gotcha the README didn't hit: the flight payload is embedded inside a <script> tag as an escaped JS string, so a value containing a literal " in your grep pattern may not match — match the plain text instead, the way the command above does.
Exercise 5: Chunk-diff a page with two Client Components against one with none
Scenario: Section 6 diffed /store/quick-add/p1 against /store/about. Confirm the same page also differs from a page that has its own content but no Client Components of its own.
What to do: Diff /store/quick-add/p1's chunk list against /store/search/silk's (a page with real, page-specific content, but no Client Components, from Part 2). State how many extra chunks you find.
Sample output (run for real against this course's harness):
$ diff <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/quick-add/p1.html | sort -u) \
<(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/search/silk.html | sort -u)
2d1
< chunks/0ms5w_5g_mbkv.js
(The exact chunk hash varies between builds.)
💡 Hint: The result should be the same "exactly one extra chunk" finding as section 6 — /store/search/silk is just as pure-server a baseline as /store/about, confirming the baseline choice in section 6 wasn't a coincidence.
Exercise 6: Reproduce the Date-crosses-the-boundary finding yourself
Scenario: Section 2's "going deeper" note claims a Date object survives the boundary intact. Confirm it yourself rather than trusting the README.
What to do: Build a scratch Client Component taking a when: Date prop, rendering when instanceof Date and when.toISOString(). Pass it a literal new Date("2026-01-01T00:00:00.000Z") from a scratch Server Component page. Build and grep the real output.
Sample output (run for real against this course's harness):
$ npm run build
$ grep -o 'real Date on the client[^<]*' .next/server/app/store/ex-date.html
real Date on the client<!-- -->: <!-- -->2026-01-01T00:00:00.000Z
💡 Hint: If you change the literal to new Date() (no argument — "now") instead, expect a different real error: Part 5's TOOLING.md-and-README-documented rejection of non-deterministic values during prerendering, not a serialization error. Try it and see which one you actually get.
Exercise 7: Reproduce the class-instance rejection yourself
Scenario: Section 2 also claims a class instance never crosses the boundary, even with plain fields. Confirm it yourself. What to do: Define a small class (two fields, a constructor, nothing else) in a scratch Server Component page. Pass an instance of it as a prop to a scratch Client Component. Build and capture the real error. Then switch to a plain object literal with the same two fields and confirm it builds and renders.
Sample output (run for real against this course's harness):
$ npm run build
...
Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.
{money: {amount: 1299, currency: "INR"}}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
After switching to a plain object:
$ npm run build
$ grep -o 'INR[^<]*1299' .next/server/app/store/ex-class.html
INR<!-- --> <!-- -->1299
💡 Hint: The error prints the object's own fields ({amount: 1299, currency: "INR"}) even while rejecting it — React can clearly see the data, it's specifically the class wrapper it refuses.
Next
Part 7: Streaming and Suspense
Show the solutions for Part 6 (7 files)
solutions/ex01.tsx
// Solution to Exercise 1. Drop in as
// harness/app/store/_components/FavoriteToggle.tsx, composed into a
// scratch page under harness/app/store/(shop)/.
"use client";
import { useState } from "react";
export function FavoriteToggle({ productId }: { productId: string }) {
const [favorited, setFavorited] = useState(false);
return (
<button type="button" onClick={() => setFavorited((value) => !value)} aria-pressed={favorited}>
{favorited ? "★ favorited" : "☆ favorite"} ({productId})
</button>
);
}
// harness/app/store/(shop)/ex1-favorite/page.tsx:
//
// import { FavoriteToggle } from "../../_components/FavoriteToggle";
//
// export default function Ex1FavoritePage() {
// return (
// <main>
// <h1>Favorite demo</h1>
// <FavoriteToggle productId="p1" />
// </main>
// );
// }
// $ npm run build
// ...
// ├ ○ /store/ex1-favorite
// ...
// $ grep -o '<button[^>]*>.*</button>' .next/server/app/store/ex1-favorite.html
// <button type="button" aria-pressed="false">☆ favorite<!-- --> (<!-- -->p1<!-- -->)</button>
//
// Delete both files afterward.
solutions/ex02.md
# Solution to Exercise 2
**The broken version** — add an `onToggled` prop to Exercise 1's `FavoriteToggle` and pass a server-defined function into it:
```tsx
// FavoriteToggle.tsx
"use client";
import { useState } from "react";
export function FavoriteToggle({ productId, onToggled }: { productId: string; onToggled: () => void }) {
const [favorited, setFavorited] = useState(false);
return (
<button type="button" onClick={() => { setFavorited((value) => !value); onToggled(); }} aria-pressed={favorited}>
{favorited ? "★ favorited" : "☆ favorite"} ({productId})
</button>
);
}
```
```tsx
// Ex1FavoritePage.tsx (Server Component)
<FavoriteToggle
productId="p1"
onToggled={() => console.log("toggled, on the server, which is the whole problem")}
/>
```
Real build error, captured against this harness:
```text
$ npm run build
...
Error: Event handlers cannot be passed to Client Component props.
{productId: "p1", onToggled: function onToggled}
^^^^^^^^^^^^^^^^^^
If you need interactivity, consider converting part of this to a Client Component.
```
**The fix** — remove the prop entirely; `FavoriteToggle` already owns the only state that matters:
```tsx
export function FavoriteToggle({ productId }: { productId: string }) {
const [favorited, setFavorited] = useState(false);
return (
<button type="button" onClick={() => setFavorited((value) => !value)} aria-pressed={favorited}>
{favorited ? "★ favorited" : "☆ favorite"} ({productId})
</button>
);
}
```
Rebuilds clean. Delete every file this exercise and Exercise 1 added afterward.
solutions/ex03.md
# Solution to Exercise 3
Add `"use client"` as the very first line of `harness/app/store/(shop)/go/[id]/page.tsx` (which exports `generateStaticParams` and calls `redirect()`, both Part 3 features), leaving everything else in the file untouched:
```tsx
"use client";
import { redirect } from "next/navigation";
import { products } from "../../../lib/products";
export function generateStaticParams() {
return products.map((product) => ({ id: product.id }));
}
export default async function GoPage({ params }: PageProps<"/store/go/[id]">) {
const { id } = await params;
redirect(`/store/products/${id}`);
}
```
Real build error, captured against this harness:
```text
$ npm run build
...
Error: Turbopack build failed with 1 error:
./app/store/(shop)/go/[id]/page.tsx:13:8
Error: Next.js can't recognize the exported `generateStaticParams` field in route. App pages cannot use both "use client" and export function "generateStaticParams()".
13 | export function generateStaticParams() {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
14 | return products.map((product) => ({ id: product.id }));
15 | }
```
Same error shape as the README's section 4 (`/store/quick-add/[id]`), confirming it's a general rule about the page-level combination of `"use client"` and `generateStaticParams`, not something specific to one route.
Remove the `"use client"` line and rebuild to confirm the route table and the real redirect behavior (Part 3's `307`/`NEXT_REDIRECT` proof) are back exactly as before.
solutions/ex04.tsx
// Solution to Exercise 4. Drop in as harness/app/store/_scratch/ex4/Tabs.tsx
// and harness/app/store/_scratch/ex4/SupplierCard.tsx, composed from a
// scratch page under harness/app/store/(shop)/.
"use client";
import { useState } from "react";
export function Tabs({
labelA,
labelB,
panelA,
panelB,
}: {
labelA: string;
labelB: string;
panelA: React.ReactNode;
panelB: React.ReactNode;
}) {
const [active, setActive] = useState<"a" | "b">("a");
return (
<div>
<button type="button" onClick={() => setActive("a")}>
{labelA}
</button>
<button type="button" onClick={() => setActive("b")}>
{labelB}
</button>
<div>{active === "a" ? panelA : panelB}</div>
</div>
);
}
// SupplierCard.tsx — a plain Server Component, no "use client":
//
// export function SupplierCard({ name, city }: { name: string; city: string }) {
// return <p>{name}, {city}</p>;
// }
// Ex4TabsPage.tsx — the Server Component page that wires both together:
//
// import { findProduct } from "../../lib/products";
// import { ProductSpecs } from "../../_components/ProductSpecs";
// import { Tabs } from "../../_scratch/ex4/Tabs";
// import { SupplierCard } from "../../_scratch/ex4/SupplierCard";
//
// export default function Ex4TabsPage() {
// const product = findProduct("p1")!;
// return (
// <main>
// <Tabs
// labelA="Details"
// labelB="Supplier"
// panelA={<ProductSpecs product={product} />}
// panelB={<SupplierCard name="Jaipur Blue Pottery Co-op" city="Jaipur" />}
// />
// </main>
// );
// }
// $ npm run build
// $ grep -o 'Jaipur Blue Pottery Co-op' .next/server/app/store/ex4-tabs.html
// Jaipur Blue Pottery Co-op
//
// The raw payload around that match (panelB is the inactive tab, since
// Tabs defaults to "a"):
// "panelB":["$","p",null,{"children":["Jaipur Blue Pottery Co-op",", ","Jaipur"]}]
//
// Delete harness/app/store/_scratch/ex4/ and
// harness/app/store/(shop)/ex4-tabs/ afterward.
solutions/ex05.md
# Solution to Exercise 5
No files to add or remove — this exercise only reads existing build output, against the harness's canonical state (this part's `quick-add` pages present, Part 2's `search` pages present):
```text
$ npm run build
$ diff <(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/quick-add/p1.html | sort -u) \
<(grep -o 'chunks/[A-Za-z0-9_.-]*\.js' .next/server/app/store/search/silk.html | sort -u)
2d1
< chunks/0ms5w_5g_mbkv.js
```
One extra chunk, same count as the README's section 6 diff against `/store/about` — confirming the baseline page's choice doesn't matter, as long as it genuinely has no Client Components of its own. `/store/search/silk` has real, page-specific content (Part 2's search results) but, like `/store/about`, no interactivity — both are equally valid "zero Client Component" baselines.
(The exact chunk hash is a build artifact and will differ on your own build — rerun the diff rather than trusting this filename.)
solutions/ex06.tsx
// Solution to Exercise 6. Drop in as
// harness/app/store/_scratch/ex-date/DateShow.tsx, with a scratch Server
// Component page passing it a literal Date.
"use client";
export default function DateShow({ when }: { when: Date }) {
return (
<p>
{when instanceof Date ? "real Date on the client" : "not a Date"}: {when.toISOString()}
</p>
);
}
// harness/app/store/(shop)/ex-date/page.tsx:
//
// import DateShow from "../../_scratch/ex-date/DateShow";
//
// export default function ExDatePage() {
// return <DateShow when={new Date("2026-01-01T00:00:00.000Z")} />;
// }
// $ npm run build
// $ grep -o 'real Date on the client[^<]*' .next/server/app/store/ex-date.html
// real Date on the client<!-- -->: <!-- -->2026-01-01T00:00:00.000Z
//
// Swapping the literal for `new Date()` (no argument) produces a
// different, unrelated error — Part 5's cacheComponents rejection of a
// non-deterministic value read during prerendering, the same family of
// error as that part's "going deeper" note on timers, not a
// serialization error at all:
// Error: Route "/store/ex-date": Next.js encountered the unstable value `new Date()` while prerendering.
//
// Delete harness/app/store/_scratch/ex-date/ and
// harness/app/store/(shop)/ex-date/ afterward.
solutions/ex07.md
# Solution to Exercise 7
**The broken version** — a scratch Client Component and a scratch Server Component page that passes it a class instance:
```tsx
// harness/app/store/_scratch/ex-class/ClassShow.tsx
"use client";
export default function ClassShow({ money }: { money: { amount: number; currency: string } }) {
return <p>{money.currency} {money.amount}</p>;
}
```
```tsx
// harness/app/store/(shop)/ex-class/page.tsx
import ClassShow from "../../_scratch/ex-class/ClassShow";
class Money {
constructor(public amount: number, public currency: string) {}
}
export default function ExClassPage() {
const price = new Money(1299, "INR");
return <ClassShow money={price} />;
}
```
Real build error, captured against this harness:
```text
$ npm run build
...
Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.
{money: {amount: 1299, currency: "INR"}}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
**The fix** — a plain object literal with the identical two fields, no class involved:
```tsx
export default function ExClassPage() {
const price = { amount: 1299, currency: "INR" };
return <ClassShow money={price} />;
}
```
Rebuilds clean and renders correctly:
```text
$ npm run build
$ grep -o 'INR[^<]*1299' .next/server/app/store/ex-class.html
INR<!-- --> <!-- -->1299
```
Delete `harness/app/store/_scratch/ex-class/` and `harness/app/store/(shop)/ex-class/` afterward.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Thinking "use client" marks "this one component" |
It marks the whole module, and by extension everything that module imports — reproduced structurally throughout this part | Put the directive on the smallest file that actually needs client APIs, and keep its imports equally small |
Marking a whole page "use client" for one interactive widget |
Real build error if the page also exports generateStaticParams (section 4) — and even without that export, it ships more JavaScript than necessary and loses direct server data access |
Push "use client" down to the leaf component; compose it into a Server Component page (section 1) |
| Passing a Server Component's own function as a prop to a Client Component | Functions can't be serialized across the boundary — real error reproduced in section 3 | Let the Client Component own its own event handlers; reach for a Server Action (Stage 3) only when the server genuinely needs to be called back |
Trying to import a Server Component from inside a "use client" file |
Not legal — a Client Component file can only ever receive server-rendered content as children/props, never import it |
Use the children-slot composition pattern from section 5 |
| Assuming "serializable" means "JSON only" | Date objects cross the boundary intact, verified in section 2's "going deeper" note — the real rule is "serializable by React," not "serializable by JSON.stringify" |
Test anything beyond plain strings/numbers/booleans/arrays/objects before relying on it crossing the boundary |
| Passing a class instance as a prop, even one holding only plain fields | Real build error — "Classes or null prototypes are not supported," verified in section 2 | Pass a plain object literal with the same fields instead |
Assuming a collapsed <Suspense>-free panel means its content hasn't loaded yet |
ExpandablePanel's children are already in the initial HTML's RSC payload, proven in section 5 — only the display is deferred, not the data |
Don't add a loading state for content that's already server-rendered and just visually hidden |
Quick recap
"use client"marks a module boundary — the file and everything it statically imports — not just the one component you're thinking about.- Push the boundary to the smallest leaf that needs browser state or event handlers; the chunk-diffing technique from Part 5 makes the resulting bundle size countable, not guessed.
- Props crossing from a Server Component to a Client Component must be serializable by React — more generous than plain JSON (
Dateworks, verified directly), but a function never does, and neither does a class instance, even with plain fields. - Marking an entire page
"use client"can fail outright (a dynamic route'sgenerateStaticParamsis incompatible with it) well before "it ships too much JS" becomes the concern. childrenis the one legal way to get server-rendered content inside a Client Component's boundary — never a direct import, proven by inspecting the real RSC payload.- The server-rendered HTML a Client Component produces on first load already has its real markup; only event-handler wiring (hydration) waits for the JavaScript to arrive.
Checklist
- I can explain why
"use client"is a module-boundary directive, not a per-component switch. - I built a leaf Client Component that receives only serializable props and manages its own state.
- I triggered the real "event handlers cannot be passed to Client Component props" error myself and reverted it.
- I triggered the real
"use client"+generateStaticParamsbuild error myself and reverted it. - I built a Client Component that takes server-rendered
childrenand proved, by reading the raw HTML payload, that the content was already there before any interaction. - I diffed a page's chunk list against a pure-server baseline and found the exact chunk its Client Components added.