Thuta Learning
Next.js
IntermediateWeb DevelopmentIntermediate

Server Components and Client Components

Next.jsLesson 1235 min

What you'll walk away with

  • Decide whether a component should be a Server Component or a Client Component
  • Explain how a "use client" boundary pulls the modules it imports into the client bundle
  • Pass data from a Server Component to a Client Component through serializable props
  • Keep secrets and database code from reaching the client

Explain it simply

Server and Client Components in plain language

A restaurant has a kitchen and tables. Cooking and opening the storeroom happen in the kitchen, out of the guests' sight. Adding salt or moving a plate happens at the table, done by the guest. Server Components are the kitchen; Client Components are the table.

In the App Router every page and layout is a Server Component by default. Only the small parts that must react to clicks or remember state get "use client" at the top of their file and are sent to the browser.

Problem → Why → Solution

The problem: one Like button drags the whole page to the browser

The note page needs a Like button, so a developer adds useState. Seeing the 'useState only works in Client Components' error, they put "use client" at the top of page.tsx. The error goes away, but now the page cannot be async and can no longer read from the database directly. Worse, the database client import is still there, so server-only code tries to get into the browser bundle.

app/notes/[id]/page.tsx
"use client"; // added only to silence the useState error
import { useState } from "react";
import { db } from "@/lib/db"; // database code is now imported by client code

export default function NotePage() {
  const [likes, setLikes] = useState(0);
  // can no longer write: const note = await db.note.find(...)
  return <button onClick={() => setLikes(likes + 1)}>Like ({likes})</button>;
}

Why this matters

"use client" declares 'this file and everything it imports also runs in the browser'. Making a whole page client-side grows the JavaScript bundle, loses the ability to fetch data on the server, and risks leaking secrets. The fix is to split out only the button as a Client Component.

Core concept: "use client" is a boundary in the module tree

Server Components run only on the server, and their code never reaches the browser. That is why they can use async/await to query a database directly, use API keys safely, and add nothing to the JavaScript bundle. Their rendered result is sent to the client in a compact format called the React Server Component Payload (RSC Payload). On later navigations the browser fetches only that payload for the new route, not a whole new HTML document.

Client Components are for useState, useEffect, event handlers such as onClick, browser APIs such as window and localStorage, and custom hooks. Despite the name, on the first load they are still prerendered to HTML on the server and then hydrated in the browser; hydration means attaching event handlers to the existing HTML so it becomes interactive.

"use client" goes at the very top of the file, above the imports. It declares a boundary rather than a single component: every module that file imports and every component it renders directly joins the client bundle, with no need for its own directive. So the lower in the tree you place the boundary, at the smallest interactive leaf, the smaller the bundle.

You needComponent type
Fetch from a database or API, use secretsServer Component
useState, onClick, onChangeClient Component
window, localStorage, geolocationClient Component
Static markup with no interactivityServer Component (default)

A Server Component hands data to a Client Component through props, but props travel over the network, so they must be values React can serialize: strings, numbers, booleans, arrays, plain objects and a few built-ins such as Date. Ordinary functions and class instances cannot be passed.

Deciding where the boundary goes
  1. Default: Server Component
  2. Needs state/events/browser APIs?
  3. Split only that leaf into a file
  4. Server passes serializable props

Treat "use client" as choosing which code ships to the browser, not as a way to silence an error.

General pattern

server parent + client leaf
// parent.tsx (Server Component: no directive)
export default async function Parent() {
  const data = await loadData();
  return <InteractiveLeaf initial={data.value} />;
}

// interactive-leaf.tsx
"use client";
export function InteractiveLeaf({ initial }: { initial: number }) {
  const [value, setValue] = useState(initial); // state lives here only
  return <Control value={value} onChange={setValue} />;
}

The server parent fetches data and passes it as a serializable prop. "use client" appears only in the interactive leaf's file, and the state lives there too.

Worked example: a server page with a client counter

The code block shows two files separated by comments. The page reads the note count on the server and hands it to Counter as a number prop. Only Counter needs browser JavaScript.

tsx
// app/page.tsx — Server Component
import { Counter } from "./counter";
import { getNoteCount } from "@/lib/notes";

export default async function Page() {
  const count = await getNoteCount();
  return <Counter initialCount={count} />;
}

// app/counter.tsx — Client Component
"use client";
import { useState } from "react";

export function Counter({ initialCount }: { initialCount: number }) {
  const [count, setCount] = useState(initialCount);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Code breakdown

  1. Async server pageexport default async function Page() {

    No directive, so it is a Server Component, and being async it can await data directly.

  2. Server-side dataconst count = await getNoteCount();

    getNoteCount runs only on the server, so the database connection and credentials never reach the browser.

  3. Serializable propreturn <Counter initialCount={count} />;

    A number prop is a value that fits into the RSC Payload, so it crosses the boundary without trouble.

  4. The client boundary"use client";

    Marks counter.tsx as the start of the client module tree. The page file does not carry this directive.

  5. State in the leafconst [count, setCount] = useState(initialCount);

    State starts from the server's value and grows in the browser on every click, without asking the server again.

You should see
The initial count from the server appears, and it increases in the browser on every button click.

Passing Server Components into Client Components as children

If a Client Component imports a Server Component, that component is pulled into the client bundle. To keep it a Server Component, pass it from a server parent as children (or another prop). The children are rendered on the server ahead of time, and only the result is placed inside the Client Component.

app/notes/page.tsx
import Collapsible from "./collapsible"; // "use client" inside
import NoteList from "./note-list"; // async Server Component

export default function NotesPage() {
  return (
    <Collapsible title="My notes">
      <NoteList /> {/* rendered on the server, passed in as children */}
    </Collapsible>
  );
}

Guard secrets with server-only

Next.js replaces environment variables without the NEXT_PUBLIC_ prefix with an empty string in the client bundle. To stop client code from importing database code by accident, add import "server-only" at the top of that file; importing it from the client then fails the build.

In real projects

In real projects

In well-structured Next.js codebases there are only a few "use client" files, and nearly all of them sit near the bottom of the tree. On a product page the photos, description and review list are Server Components, while only the 'Add to cart' button and the image carousel are Client Components.

  • React context providers for things like the theme or the cart live in one "use client" file and wrap only {children} in the root layout.
  • A third-party component that lacks "use client", such as a chart library, is re-exported from a small Client Component wrapper file before Server Components use it.
  • Files such as lib/db.ts start with import "server-only", so if someone imports them from client code by mistake the build catches it.

Common mistakes

Common mistakes

Marking a whole page "use client" for one hook

A client page loses async data fetching, metadata exports and server-only imports, and everything it imports joins the bundle. Move only the part that needs the hook into a new file.

Passing a function from server to client as a prop

Writing <Counter onChange={(n) => save(n)} /> in a Server Component fails because a function cannot be serialized. Write the click logic inside the Client Component, and use a Server Action when data must go back to the server (lesson 18).

Importing a database or a secret into a Client Component

Importing lib/db from a client file can fail the build because of Node-only modules, and it risks putting secrets in the bundle. Fetch the data in a Server Component and pass only the fields you need as props.

Best practices

Best practices

  • Start every new component as a Server Component and add "use client" only when it truly needs interactivity.
  • Naming client files with suffixes such as -button, -form or -toggle makes it easy to see which files ship to the browser.
  • Instead of passing a whole database record, pass only the fields the Client Component actually uses.

Mini challenge

Mini challenge: a profile page with a follow button

Write the profile page as a Server Component that reads the follower count on the server. Write the follow button as a separate Client Component that toggles between Follow and Following on each click and adjusts the count.

  • page.tsx has no "use client" and is async
  • follow-button.tsx starts with "use client"
  • The server passes initialFollowers as a number prop
  • The button text and the count change on every click
app/users/[username]/
// app/users/[username]/page.tsx  (Server Component)
import { FollowButton } from "./follow-button";
import { getProfile } from "@/lib/profiles";

export default async function ProfilePage(/* TODO: params */) {
  // TODO: load the profile on the server
  // TODO: render the name and <FollowButton initialFollowers={...} />
}

// app/users/[username]/follow-button.tsx
// TODO: make this a Client Component
export function FollowButton({ initialFollowers }: { initialFollowers: number }) {
  // TODO: keep "following" and the count in state
  // TODO: toggle both on click
}

Expected: Opening the page shows the server's count in the HTML, for example 'Follow · 41 followers'. A click changes it to 'Following · 42 followers' and another click changes it back. Only the button's code is shipped as JavaScript.

Show hint

Keep const [following, setFollowing] = useState(false) in the button and compute the count as initialFollowers + (following ? 1 : 0); then you do not need two pieces of state.

Show solution
app/users/[username]/
// app/users/[username]/page.tsx  (Server Component)
import { FollowButton } from "./follow-button";
import { getProfile } from "@/lib/profiles";

export default async function ProfilePage({
  params,
}: {
  params: Promise<{ username: string }>;
}) {
  const { username } = await params;
  const profile = await getProfile(username); // { name, followers }
  return (
    <section>
      <h1>{profile.name}</h1>
      <FollowButton initialFollowers={profile.followers} />
    </section>
  );
}

// app/users/[username]/follow-button.tsx
"use client";
import { useState } from "react";

export function FollowButton({ initialFollowers }: { initialFollowers: number }) {
  const [following, setFollowing] = useState(false);
  const count = initialFollowers + (following ? 1 : 0);
  return (
    <button onClick={() => setFollowing(!following)}>
      {following ? "Following" : "Follow"} · {count} followers
    </button>
  );
}

Quick quiz 1 / 3

Which of these components must have "use client"?

Quick quiz 2 / 3

A Server Component page renders <Counter initialCount={5} onReset={() => console.log("reset")} />, where Counter is a Client Component. What happens?

Quick quiz 3 / 3

Are "use client" Client Components rendered on the server at all?

What to remember

  • Pages and layouts are Server Components by default and do data fetching and secret handling on the server.
  • "use client" is a boundary: the file and everything it imports join the client bundle, so keep it on interactive leaves.
  • Props from server to client must be serializable; functions cannot be passed.
  • Server Components can be passed into Client Components as children, and import "server-only" protects secrets.

Next.js — Server and Client Components — Next.js

Next.js — Server and Client Components — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Server Components and Client Components | Thuta Learning