Skip to content

Client Components

The Course
•
20 min study

Anything that responds to the reader, with state, event handlers or effects, has to run in the browser. Those are client components.

Like buttons Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Hub</header> {children} </body> </html> ); } import { getTopics } from "../lib/topics.js"; import LikeButton from "./LikeButton.jsx"; export default async function HomePage() { const topics = await getTopics(); return ( <main> <h1>Topics</h1> {topics.map((topic) => ( <div key={topic.id} className="card"> {topic.title} <LikeButton /> </div> ))} </main> ); } "use client"; import { useState } from "react"; export default function LikeButton() { const [likes, setLikes] = useState(0); console.log("LikeButton rendered with", likes); return <button onClick={() => setLikes(likes + 1)}>♥ {likes}</button>; } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } // Pretend database: in a real app this would query a database or call an API. const topics = [ { id: 1, title: "Pages and routes", day: 1, minutes: 20 }, { id: 2, title: "Layouts and links", day: 1, minutes: 20 }, { id: 3, title: "Server components", day: 2, minutes: 20 }, { id: 4, title: "Client components", day: 2, minutes: 20 }, { id: 5, title: "Dynamic routes", day: 3, minutes: 25 }, ]; export async function getTopics() { console.log("Reading topics from the database"); await new Promise((resolve) => setTimeout(resolve, 200)); return topics; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.

Press a few hearts. Then look at the console.

"use client"

JavaScript
"use client";

import { useState } from "react";

export default function LikeButton() {
  const [likes, setLikes] = useState(0);
  …
}

The "use client" line at the very top marks the file as client code. It's an ordinary React component, as in the React courses: useState, onClick and effects all work.

The two kinds together

The page is still a server component: it loads the topics and renders a LikeButton for each. Next.js sends the page's HTML, plus the code for the client module graph needed by LikeButton, so the browser can hydrate that part of the page: attach its interactive behaviour. On an initial load, Client Components can also be rendered on the server to produce HTML; Day 2's last lesson explains why browser-only values need care:

JSX
export default async function HomePage() {
  const topics = await getTopics();

  return (
    <main>
      <h1>Topics</h1>
      {topics.map((topic) => (
        <div key={topic.id} className="card">
          {topic.title} <LikeButton />
        </div>
      ))}
    </main>
  );
}

The console shows the split: [server] Reading topics… from the server, and LikeButton rendered with 0 five times, without [server], from the browser.

Keep "use client" for the parts that need it. Here, the list and the heading stay on the server, and only the small buttons are client code. Less code goes to the browser, and the data stays where it's loaded.

Predict

What happens if you put onClick={() => console.log("hi")} on the page's <h1>, in the server component?

Check your prediction

An error: Event handlers cannot be passed to Client Component props. A server component's output is HTML sent to the browser, and a function can't be sent along with it. Real Next.js shows the same message. Interactivity belongs in a client component. Undo the change.

Props cross the boundary

A server component can pass data to a client component through props, as usual. Next.js sends the props to the browser with the HTML, so they must be plain data: strings, numbers, arrays, objects, dates. The next exercise does that.

Exercise

Name each button

Every button reads ♥ 0 to a screen reader, with no topic. Give each one an accessible name, such as Like Dynamic routes, using the topic's title from the server.

Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Hub</header> {children} </body> </html> ); } import { getTopics } from "../lib/topics.js"; import LikeButton from "./LikeButton.jsx"; export default async function HomePage() { const topics = await getTopics(); return ( <main> <h1>Topics</h1> {topics.map((topic) => ( <div key={topic.id} className="card"> {topic.title} <LikeButton /> </div> ))} </main> ); } "use client"; import { useState } from "react"; export default function LikeButton() { const [likes, setLikes] = useState(0); console.log("LikeButton rendered with", likes); return <button onClick={() => setLikes(likes + 1)}>♥ {likes}</button>; } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } // Pretend database: in a real app this would query a database or call an API. const topics = [ { id: 1, title: "Pages and routes", day: 1, minutes: 20 }, { id: 2, title: "Layouts and links", day: 1, minutes: 20 }, { id: 3, title: "Server components", day: 2, minutes: 20 }, { id: 4, title: "Client components", day: 2, minutes: 20 }, { id: 5, title: "Dynamic routes", day: 3, minutes: 25 }, ]; export async function getTopics() { console.log("Reading topics from the database"); await new Promise((resolve) => setTimeout(resolve, 200)); return topics; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

The button doesn't know which topic it belongs to: only the page, a server component, has the topics. A server component passes data to a client component the same way any component does.

Hint 2: a first step

Give LikeButton a prop from the page and log it inside the button. Each button should log its own topic's title. Then use it for the name: the aria-label attribute sets a button's accessible name.

Show one solution

In app/page.jsx:

JSX
<LikeButton title={topic.title} />

In app/LikeButton.jsx:

JSX
export default function LikeButton({ title }) {
  …
  return (
    <button aria-label={`Like ${title}`} onClick={() => setLikes(likes + 1)}>
      ♥ {likes}
    </button>
  );
}

The title is a plain string, so it can cross from the server component to the client component as a prop. aria-label replaces the name a screen reader would build from the visible text, ♥ 0, so the count stays on screen and the name says what the button does. Adding the title to the visible text would also name it, but crowds every button.

Was this article helpful?

Your response is saved on this device.