Sub topic 3
The "use client" boundary
This chapter assumes you know React components, props, useState and useEffect, and ES module imports. It also assumes you have read the previous chapter on what Server Components and Client Components can do. Here you will learn what the "use client" directive marks, how it spreads through the import graph, and how to place it well.
What the directive marks
In a framework that supports React Server Components, every module starts on the server side. The "use client" directive changes that for one module. It tells the bundler: this file, and everything it imports, must be able to run in the browser.
Here is the Client Component from the earlier example:
// app/Counter.js
'use client';
import { useState } from 'react';
export default function Counter({ initial }) {
const [count, setCount] = useState(initial);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}Three facts about this directive matter for everything else in the chapter.
- It applies to a module (a file), not to a single component. Every export of the file becomes client code.
- It marks an entry point into client code. It does not mean the component skips the server. A framework that also does server-side rendering (SSR) still renders Client Components to HTML on the server. The next chapters cover this.
- There is no matching
"use server"directive for Server Components. Server is the default. The"use server"directive has a different meaning, covered in the Server Functions chapter.
Where the directive must go
The directive is a string literal at the very top of the file. Only comments may come before it. If you put it after an import, it is just an unused string, and the file stays a Server Component. The error you then see is usually a hook such as useState being called in a Server Component.
// Wrong: the directive comes after an import, so it is ignored
import { useState } from 'react';
'use client';
// Right
'use client';
import { useState } from 'react';Both single and double quotes work. Backticks do not, because a template literal is not a directive.
The boundary spreads down the import graph
You do not need to write "use client" in every file. Once a module is marked, every module it imports is bundled for the client too. The directive creates a boundary in the module graph, and everything on the far side of it is client code.
The boundary follows imports, not the render tree. This distinction causes most confusion. Look at this code.
// app/Counter.js
'use client';
import { formatCount } from './format'; // pulled into the client bundle
import Comments from './Comments'; // also pulled into the client bundleIf Comments.js is a Server Component that reads a database, importing it from a client file does not keep it on the server. The bundler treats it as client code, and it will fail or run in the wrong place. If a Client Component needs server-rendered content, do not import it. Pass it in as children or a prop. The composition chapter covers that pattern in detail.
A module with no directive can be on either side. A file such as format.js that has only pure functions works on the server when imported by a Server Component, and on the client when imported by a Client Component. The same file may even appear in both bundles.
What the boundary does to the payload
At build time, the bundler replaces each import of a boundary module, when it is imported from server code, with a client reference. This is a small description of where to find the code (a module ID, the chunk files to load, and the export name). It is not the code itself.
When the server renders <Counter initial={1} />, it does not run Counter. It writes a row that points to it, using the simplified payload from the spine:
1:I["app/Counter.js",["chunk-counter.js"],"default"]
0:["$","main",null,{"children":[["$","h1",null,{"children":"Posts"}],["$","$L1",null,{"initial":1}]]}]Row 1 is the client reference. In row 0, "$L1" stands in where the element type would be. The props object {"initial":1} is sent as data. The exact syntax differs between React versions and frameworks, so read it for its structure and not as a stable format.
This shows what the boundary costs and saves:
- Server Component code that sits above the boundary is never shipped. Only its output (elements) is in the payload.
- Client Component code, and everything it imports, is shipped as JavaScript the browser must download and run.
- The props at the boundary are serialized into the payload. They must be values the format can represent. The next chapters cover this in detail, but one rule is important now: a function defined in a Server Component cannot be passed as a prop to a Client Component.
Placing the boundary
The aim is to push the boundary as far down the tree as you can. Make the smallest interactive part a Client Component, and leave the rest on the server.
Consider a product page with a long description and a "Like" button. This version marks the whole page:
// app/ProductPage.js
'use client';
import { useState } from 'react';
import { marked } from 'marked'; // a large Markdown library
export default function ProductPage({ markdown }) {
const [liked, setLiked] = useState(false);
return (
<article>
<div dangerouslySetInnerHTML={{ __html: marked.parse(markdown) }} />
<button onClick={() => setLiked(!liked)}>
{liked ? 'Liked' : 'Like'}
</button>
</article>
);
}The Markdown library now ships to every visitor, only to convert text that could have been converted once on the server. Moving the boundary down fixes that:
// app/LikeButton.js
'use client';
import { useState } from 'react';
export default function LikeButton() {
const [liked, setLiked] = useState(false);
return (
<button onClick={() => setLiked(!liked)}>
{liked ? 'Liked' : 'Like'}
</button>
);
}
// app/ProductPage.js (Server Component, no directive)
import { marked } from 'marked';
import LikeButton from './LikeButton';
export default function ProductPage({ markdown }) {
return (
<article>
<div dangerouslySetInnerHTML={{ __html: marked.parse(markdown) }} />
<LikeButton />
</article>
);
}Now marked runs only on the server, and the payload carries the finished HTML elements plus one client reference for the button. Treat markdown as trusted content in this example. Rendering untrusted Markdown as raw HTML needs sanitizing.
The same logic applies to a larger layout. If a page needs one piece of state, such as a search box with a text field, move that state into a small component. Do not mark the whole layout.
When a higher boundary is fine
Do not chase the smallest boundary at any cost. A boundary is reasonable higher up when:
- Most of the subtree is interactive anyway, such as a drawing editor or a form with many controlled inputs.
- The subtree depends on browser-only libraries that touch
windowordocument. - Splitting would force you to pass many props across the boundary for no savings.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `useState` (or another hook) fails in a component | The file has no effective `"use client"`, or the directive is below an import | Put the directive first in the file, or move the stateful part into its own Client Component |
| An `onClick` handler error on a Server Component | Event handlers are not allowed on elements rendered only on the server | Move the interactive element into a Client Component |
| Server-only code (database client, secret) appears in the client bundle | A Client Component imports it, directly or through another module | Remove the import, and pass data in as props. Many frameworks offer a `server-only` package that throws if such a module is imported on the client |
| A function prop cannot be passed to a Client Component | Functions are not serializable across the boundary | Define the function inside the Client Component, or use a Server Function (covered later) |
| The bundle is larger than expected | The directive sits too high in the tree, or a barrel file (`index.js` that re-exports many modules) pulls in extra code | Move the boundary down, and import from specific files |
Edge cases to remember
- Importing a Client Component into another Client Component needs no second directive. Everything under the boundary is already client code.
- A Server Component cannot be imported by a Client Component, but it can be rendered inside one if it is passed as
childrenor another prop from a Server Component above. - A module that a Client Component imports can end up included in the client bundle even if you never use some of its exports, depending on how well the bundler removes unused code.
- Third-party libraries that use hooks or browser APIs often lack the directive. If you import one from a Server Component, it fails. Wrap it in your own small file that starts with
"use client"and re-exports it.
// app/ClientChart.js
'use client';
// Re-export so Server Components can import the library safely
export { LineChart } from 'some-chart-library';Exercise
A Server Component page imports Panel.js, which starts with 'use client'. Panel.js imports Details.js, which has no directive and is an async function that queries a database. Why is this a problem, and how would you change the design so Details keeps running on the server?
Show answer
Importing Details.js from Panel.js pulls it into the client bundle, because the boundary follows imports. An async database query cannot run there and would expose server-only code. Remove the import from Panel.js. In the page (a Server Component), render <Panel><Details /></Panel>, and have Panel display children. Details then renders on the server and arrives in the payload as finished output.