Sikau

Next.js · Day 8 · about 30 min

Client Components

"use client" for interactivity — and where to draw the line.

Interactivity where it's needed

Buttons, forms with live validation, anything with useState or onClick needs to run in the browser. Put "use client" at the top of a file and its components become Client Components. Keep them small: the rest of the page stays on the server.

The boundary

import LikeButton from "./LikeButton";
import { getDish } from "@/lib/data";

export default async function Page() {
  const dish = await getDish("momo");
  return (
    <article>
      <h1>{dish.name}</h1>
      <p>{dish.description}</p>
      <LikeButton initial={12} />
    </article>
  );
}
  • "use client" marks the boundary: that file and everything it imports run in the browser too.
  • Push client components down to the leaves (the button, not the whole page).
  • Pass server-rendered content into a client component as children to keep it on the server.
  • Client Components still render on the server for the first HTML — then React makes them interactive (hydration).

The rest of this lesson

  • Passing data across the boundaryexplain
  • The children trickexplain
  • Which needs "use client"?predict
  • Can it cross the boundary?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 19 lessons of Next.js