Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 72 ยท Server and Client Components

Client Components and "use client"

Learn what the use client directive does in Next.js: where the server-client boundary sits, when you need Client Components, how they hydrate and how they affect bundle size.

Server Components are the default, but a page you can read and never touch is not much of an app. Buttons need click handlers, forms need state, and a map or chart needs the browser. For all of that, the App Router has Client Components: ordinary React components that are sent to the browser, hydrated, and then react to the user.

You turn a file into a Client Component with one line at the top: "use client". It looks small, but it does more than label one component. It draws a boundary in your module graph, and everything on the far side of that boundary becomes part of the JavaScript the visitor downloads. This lesson explains what the directive marks, what Client Components can do, why they are still rendered on the server once, and how to keep the client bundle small. The real framework is not available on the site, so Next.js code is read-only; the runnable examples are React stand-ins that model the bundle effect and the hydration step.

When you need a Client Component

State useState, useReducer, useRef that changes UI.
Events onClick, onChange, onSubmit handlers.
Effects useEffect and anything that runs after render.
Browser APIs window, localStorage, geolocation.

If none of these apply, stay on the server.

1 / 2

The directive

Put the string "use client" as the very first statement of a file, above all imports.

TSX
// app/components/like-button.tsx (read-only)
"use client";

import { useState } from "react";

export default function LikeButton({ initialLikes }: { initialLikes: number }) {
  const [likes, setLikes] = useState(initialLikes);

  return (
    <button onClick={() => setLikes(likes + 1)}>
      {likes} likes
    </button>
  );
}

Now a Server Component can import it and render it like any other component:

TSX
// app/posts/[id]/page.tsx (read-only)
import LikeButton from "@/app/components/like-button";

export default async function PostPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const post = await getPost(id);

  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
      <LikeButton initialLikes={post.likes} />
    </article>
  );
}

The page, the heading and the paragraph stay on the server. Only LikeButton and the code it imports are shipped. The initialLikes prop crosses the boundary from server to browser, which is why props passed to a Client Component must be serializable (see Composing Server and Client Components).

The directive marks a boundary, not a single component

This is the part most people miss. "use client" does not mean "this component is a Client Component and everything else is unaffected". It means "this module is a client entry point". Every module that the file imports becomes part of the client bundle too, whether or not those modules have the directive themselves.

So if like-button.tsx imports a date-formatting library, that library is downloaded by every visitor. If you put "use client" at the top of a big layout, the whole subtree of imports comes with it, and you have lost the main advantage of Server Components. The rule of thumb: keep the directive on small, leaf-like components, as far down the tree as possible.

The stand-in below models this with a made-up module graph and invented sizes in kilobytes. Modules marked as client entries, plus everything they import, are counted in the client bundle. Start with the three small interactive modules marked, then try marking reviews.tsx or page.tsx and watch the total grow. The sizes are illustrative, not real measurements.

What does the boundary drag into the bundle?

Marking only the three small files gives a bundle of 14 + 4 + 12 + 2 = 32 KB, because search-box.tsx brings fuzzy-lib.js with it. Tick reviews.tsx and the 48 KB Markdown library arrives too, even though that library never needed to leave the server. The better fix is to keep reviews.tsx on the server and pass anything it renders that needs interactivity through a small Client Component.

Client Components also render on the server

The name is misleading, because a Client Component is not "client only". On the first request, Next.js renders Client Components to HTML on the server too, so visitors see content immediately and search engines get real markup. The browser then downloads the component's JavaScript and hydrates it: React walks through the existing HTML, attaches the event handlers and makes the component interactive.

This has two practical effects. First, until hydration finishes, a button is visible but does nothing, so keep the JavaScript small and the page responsive. Second, code that runs while rendering must also work on the server. Reading window directly in the body of a Client Component fails during the server render, so do it inside useEffect or an event handler, which only run in the browser.

TSX
// read-only
"use client";

import { useEffect, useState } from "react";

export default function ScreenWidth() {
  const [width, setWidth] = useState<number | null>(null);

  useEffect(() => {
    setWidth(window.innerWidth); // runs in the browser only
  }, []);

  return <p>{width === null ? "Measuring..." : `${width}px wide`}</p>;
}

The stand-in below makes hydration visible. It uses React's real renderToString to produce HTML, inserts that HTML into a container, and then, only when you press the button, calls the real hydrateRoot to attach the component. Click the counter before and after hydrating.

Server HTML first, interactivity after hydration

Click the counter button first: the text stays at "Clicked 0 times". Press Hydrate now, then click again and the count goes up. In Next.js the hydration step happens automatically as soon as the JavaScript has loaded; the manual button is just a way to see the gap between "visible" and "interactive".

What Client Components can and cannot do

Inside a Client Component you have everything you know from ordinary React: state, effects, refs, context, event handlers and browser APIs. Third-party packages that use these features, such as chart or map libraries, also belong in Client Components.

There are two limits. A Client Component cannot be async, because the browser cannot pause a render to wait for a database query. And it cannot import server-only code: a module that reads secrets or talks to the database must stay out of the client module graph, which Keeping Server Code on the Server covers. If a Client Component needs server data, the usual pattern is for a parent Server Component to fetch the data and pass it down as props.

Placing the directive well

Use these habits to keep bundles lean:

  • Mark leaf components. A LikeButton or a SearchBox is a good client entry. A whole page or layout is rarely one.
  • Extract the interactive part. If a page needs one button with a click handler, move that button into its own file and add the directive there instead of to the page.
  • You only need the directive once per boundary. Components imported by a client file are already client; do not add the directive to each of them.
  • Do not import a Server Component into a Client Component. It would be pulled into the client graph and lose its server powers. Pass it in as children instead, which the next lesson shows.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does adding "use client" to a file do?

    The directive marks the module as the boundary between server and client code. Its imports are bundled for the browser as well.
  2. 2. A Client Component reads window.innerWidth in the body of the component. What is the likely problem?

    Client Components are rendered to HTML on the server for the first response. Browser APIs belong in useEffect or event handlers.
  3. 3. Which is a good place for the use client directive?

    Mark small interactive leaves. Putting the directive on a layout or a data module pulls large parts of the app into the client bundle or leaks server code.
  4. 4. What is hydration?

    After the browser loads the client JavaScript, React reuses the existing HTML and makes it interactive.

Summary

  • "use client" at the top of a file makes it a client entry point; the file and everything it imports are sent to the browser.
  • Use Client Components for state, effects, event handlers and browser APIs, and keep the rest on the server.
  • Client Components are rendered to HTML on the server first, then hydrated in the browser.
  • Browser-only code must run in effects or event handlers, because the first render happens on the server.
  • Put the directive on small leaf components and pass data in through serializable props.

Next: Composing Server and Client Components