How to Split Server and Client Code with ‘use client’ in React
ReactNext.js,props,Server-side rendering,TypeScript
In React Server Components, a component is a Server Component unless you say otherwise. The boundary to the client is the point where a file starts with 'use client'. The boundary is determined by imports, not by parent-child relationships in the rendered tree. I built a small app with Next.js 16 to check which code ends up in the browser JS, and what errors appear when the boundary is placed wrongly.
Test environment: Ubuntu 24.04, Node.js 22.22.0, Next.js 16.4.3 (App Router, built with Turbopack), React 19.3.1, TypeScript 7.0.2, and Chromium (Chrome for Testing 153). I only checked the production build (next build) and next start. I did not check the display under the development server (next dev). I did not cover frameworks other than Next.js or Server Functions ('use server').
- 1. The boundary is determined by imports
- 2. The test app
- 3. Only the 'use client' files and the files they import went into the browser JS
- 4. Passing a Server Component as children keeps it on the server
- 5. Importing from a Client Component moves the code to the client side
- 6. Forgetting 'use client' on a file that uses hooks stops the build
- 7. Only serializable values can be passed as props
- 8. How to decide where to place the boundary
The boundary is determined by imports
The React reference for 'use client' states that when you write 'use client' at the top of a file, that module and all modules it imports become client code. Imported files do not need 'use client' themselves to end up on the client side.
The Next.js documentation explains that only two things cross the boundary. Code crosses through imports: anything a Client Component imports goes into the browser JS. Data crosses through props, and it must be a serializable value.
'use client' must be written before any code such as imports in the file (comments may come before it).
I drew a diagram of the import relationships in the app I used for testing.

The test app
This is a page that shows a list of cats. Reading the list from a file and displaying it happen on the server. The "like" count and opening and closing the list happen on the client. To find out which files' code ended up in the browser JS, the test app adds marker attributes (data-mark) to elements. The code in this article omits those attributes.
The file-reading code is used only on the server. The import 'server-only' at the top is explained in a later section.
// lib/cats.ts
import 'server-only';
import { readFile } from 'node:fs/promises';
export type Cat = { name: string; color: string };
// Server-only processing (reads a file)
export async function getCats(): Promise<Cat[]> {
const text = await readFile('data/cats.json', 'utf8');
return JSON.parse(text) as Cat[];
}
The component that displays the list has no 'use client', so it is a Server Component. You can make it an async function and use await inside rendering.
// app/ui/cat-list.tsx
import { getCats } from '../../lib/cats';
export default async function CatList() {
const cats = await getCats();
return (
<ul>
{cats.map((cat) => (
<li key={cat.name}>
{cat.name}({cat.color})
</li>
))}
</ul>
);
}
I put 'use client' at the top of two files that use useState and click handlers. Toggle receives the list as children.
// app/ui/toggle.tsx
'use client';
import { useState } from 'react';
export default function Toggle({ children }: { children: React.ReactNode }) {
const [open, setOpen] = useState(false);
return (
<section>
<button onClick={() => setOpen(!open)}>{open ? '一覧を閉じる' : '一覧を開く'}</button>
{open && children}
</section>
);
}
LikeButton uses a function from lib/format.ts to display the count. lib/format.ts does not have 'use client'.
// app/ui/like-button.tsx
'use client';
import { useState } from 'react';
import { formatLikes } from '../../lib/format';
export default function LikeButton({ initialLikes, updatedAt }: { initialLikes: number; updatedAt: Date }) {
const [likes, setLikes] = useState(initialLikes);
return (
<div>
<button onClick={() => setLikes(likes + 1)}>{formatLikes(likes)}</button>
<p id="updated">
updatedAt は Date か:{String(updatedAt instanceof Date)}({updatedAt.toISOString()})
</p>
</div>
);
}
// lib/format.ts
export function formatLikes(n: number): string {
return `${n} いいね`;
}
The page is a Server Component. It passes the cat count and a date to LikeButton as props, and puts CatList inside Toggle as children.
// app/page.tsx
import { getCats } from '../lib/cats';
import CatList from './ui/cat-list';
import LikeButton from './ui/like-button';
import Toggle from './ui/toggle';
export default async function Page() {
const cats = await getCats();
return (
<main>
<h1>猫の一覧({cats.length}匹)</h1>
<LikeButton initialLikes={cats.length} updatedAt={new Date('2026-10-23T00:00:00Z')} />
<Toggle>
<CatList />
</Toggle>
</main>
);
}
Only the 'use client' files and the files they import went into the browser JS
I built with next build and counted how many files in the browser JS (inside .next/static) contained a string that appears only in that file.
| File | String searched for | Number of files containing it |
|---|---|---|
app/page.tsx |
the page's marker attribute | 0 |
app/ui/cat-list.tsx |
the list's marker attribute | 0 |
lib/cats.ts |
data/cats.json |
0 |
app/ui/like-button.tsx |
the button's marker attribute | 1 |
app/ui/toggle.tsx |
一覧を開く |
1 |
lib/format.ts |
いいね |
1 |
Besides the two files with 'use client', lib/format.ts, which does not have 'use client', also ended up in the browser JS. That is because LikeButton imports it. In contrast, the code for the page, the list, and the file-reading code did not end up there.
You only need to put 'use client' on the file that forms the boundary. Files it imports end up on the client side even without it. Keep code that should stay on the server from being imported by a 'use client' file or by any file it imports, directly or further down the chain.
The Next.js documentation also recommends that you put 'use client' only on the component files that handle interaction, rather than on most of the screen, to reduce the JS sent to the browser.
Passing a Server Component as children keeps it on the server
CatList is displayed inside Toggle (a Client Component), but its code did not end up in the browser JS. That is because the Toggle file does not import CatList. The page only passes it as children. The React reference also says that the boundary is determined by imports, not by parent-child relationships.
Looking at the payload rendered on the server (the RSC payload), CatList appeared not as code but as rendered output data (only the relevant lines are shown).
12:I[87335,["$2","$11"],"default"]
13:I[30179,["$2","$11"],"default"]
6:["$","main",null,{"data-mark":"MARK_PAGE","children":[["$","h1",null,{"children":["猫の一覧(",3,"匹)"]}],["$","$L12",null,{"initialLikes":3,"updatedAt":"$D2026-10-23T00:00:00.000Z"}],["$","$L13",null,{"children":"$L14"}]]}]
14:["$","ul",null,{"data-mark":"MARK_CAT_LIST","children":[["$","li","たま",{"children":["たま","(","白",")"]}],["$","li","みけ",{"children":["みけ","(","三毛",")"]}],["$","li","くろ",{"children":["くろ","(","黒",")"]}]]}]
Lines 12 and 13 are references to Client Component code. From the props passed, $L12 is LikeButton and $L13 is Toggle. Toggle's children is $L14, and line 14 contains the list's ul and li elements as written.
I opened the page run with next start in Chromium and pressed the button.
# Right after loading
ボタン: 3 いいね
updatedAt は Date か:true(2026-10-23T00:00:00.000Z)
li の数: 0
# After pressing "like" once
ボタン: 4 いいね
# After pressing the open-list button
li: たま(白) / みけ(三毛) / くろ(黒)
ボタンを押してから送られたリクエストの数: 0
The list starts closed. When I pressed the open-list button, the three cats appeared. No requests were sent to the server between pressing the button and the list appearing. The payload already contained the rendered list (line 14) from the start, and pressing the button sent zero requests. So the list appears to have been shown without being fetched again.
Importing from a Client Component moves the code to the client side
I stopped receiving children in Toggle and instead imported CatList directly from the Toggle file. On the page side, I removed the CatList import and left only <Toggle />.
'use client';
import { useState } from 'react';
+import CatList from './cat-list';
-export default function Toggle({ children }: { children: React.ReactNode }) {
+export default function Toggle() {
const [open, setOpen] = useState(false);
return (
<section>
<button onClick={() => setOpen(!open)}>{open ? '一覧を閉じる' : '一覧を開く'}</button>
- {open && children}
+ {open && <CatList />}
</section>
);
}
The build stopped with two errors. I extracted one of them below.
./lib/cats.ts:1:1
Error: 'server-only' cannot be imported from a Client Component module
> 1 | import 'server-only';
| ^^^^^^^^^^^^^^^^^^^^^
2 | import { readFile } from 'node:fs/promises';
3 |
4 | export type Cat = { name: string; color: string };
It should only be used from a Server Component.
Import traces:
Server Component:
./lib/cats.ts
./app/page.tsx
Client Component Browser:
./lib/cats.ts [Client Component Browser]
./app/ui/cat-list.tsx [Client Component Browser]
./app/ui/toggle.tsx [Client Component Browser]
./app/ui/toggle.tsx [Server Component]
./app/page.tsx [Server Component]
Neither cat-list.tsx nor cats.ts has 'use client'. However, because toggle.tsx imports them, both ended up on the client side (Client Component Browser). The import traces at the end of the error show which path crossed the boundary.
The error came from the import 'server-only' at the top of lib/cats.ts. The Next.js documentation describes importing this server-only package to prevent server-only code from leaking into the client.
With the same change, I removed import 'server-only' from lib/cats.ts. In this version, the build stopped with an internal Turbopack error (excerpt):
FATAL: An unexpected Turbopack error occurred. A panic log has been written to (一時ファイル).
...
> Build error occurred
Error [TurbopackInternalError]: Failed to write app endpoint /page
Caused by:
- the chunking context (unknown) does not support external modules (request: node:fs/promises)
This shows that node:fs/promises cannot be loaded on the client, but it does not say which file crossed the boundary. In this case, the build stopped because the code loaded node:fs/promises. The Next.js documentation gives an example of a function that calls an external API using an environment variable (API_KEY). It explains that if such a function is imported and run on the client, variables without the NEXT_PUBLIC_ prefix are replaced with empty strings, so the code does not work as intended. (I did not test this case.) If you put server-only in files that must not reach the client, the build will report the crossing, and the cause is easier to find.
Forgetting 'use client' on a file that uses hooks stops the build
When I removed 'use client' from the top of like-button.tsx and built, the build stopped with this error (excerpt):
./app/ui/like-button.tsx:1:10
Error: You're importing a module that depends on `useState` into a React Server Component module. This API is only available in Client Components. To fix, mark the file (or its parent) with the `"use client"` directive.
Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
> 1 | import { useState } from 'react';
| ^^^^^^^^
Without 'use client', like-button.tsx, which the page imports, is treated as a Server Component. The Next.js documentation also says that components that handle state, click events, or use browser APIs should be Client Components. Such files need 'use client'.
Only serializable values can be passed as props
Props passed from a Server Component to a Client Component must be serializable values. The React reference lists strings, numbers, arrays, plain objects, Date, Map, Set, Promises, and JSX. Functions (except Server Functions) and class instances cannot be passed.
In the payload, Date appeared as the string "$D2026-10-23T00:00:00.000Z". Even so, in the browser updatedAt instanceof Date was true, so it was received as a Date.
I tried passing a function and a class instance from the page to LikeButton. In the tests, I also added props types to LikeButton (such as onLike?: () => void) to match what was passed. Each case passed the build's type check, but stopped when the page was prerendered. (Only the relevant part of each error is shown.)
// Passing a function (the name has an uppercase letter right after "on")
<LikeButton
initialLikes={cats.length}
updatedAt={new Date('2026-10-23T00:00:00Z')}
onLike={() => console.log('liked')}
/>
Error: Event handlers cannot be passed to Client Component props.
{initialLikes: 3, updatedAt: Date, onLike: function onLike}
^^^^^^^^^^^^^^^
If you need interactivity, consider converting part of this to a Client Component.
// Passing a function (the name does not have an uppercase letter right after "on")
<LikeButton
initialLikes={cats.length}
updatedAt={new Date('2026-10-23T00:00:00Z')}
getLabel={() => 'いいね'}
/>
Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
{initialLikes: 3, updatedAt: Date, getLabel: function getLabel}
^^^^^^^^^^^^^^^^^
// Passing a class instance
class Owner {
constructor(public name: string) {}
}
<LikeButton
initialLikes={cats.length}
updatedAt={new Date('2026-10-23T00:00:00Z')}
owner={new Owner('たま')}
/>
Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.
{initialLikes: 3, updatedAt: Date, owner: {name: "たま"}}
^^^^^^^^^^^^
When I passed a function, the message changed depending on the prop name. In the React source, names such as onLike and onClick, where on is followed by an uppercase letter, trigger a message saying an event handler was passed. In both cases, write click handling inside the Client Component, and pass only data such as numbers and strings from the server. That way, the data can cross the boundary.
How to decide where to place the boundary
From these results, you can decide the boundary as follows.
First, keep pages and layouts as Server Components. Only the components that use useState, click handlers, or browser APIs should go into separate files, each starting with 'use client'. Everything imported from such a file goes into the browser JS, so do not import code that should stay on the server.
When you want to place server-rendered content inside a Client Component, don't import it. Pass it as JSX through props such as children. Data passed from the server to a Client Component must be serializable. If you put import 'server-only' in files that should only run on the server, a build error will show which file crossed the boundary when that happens.
Posted by 86
Related Posts

How to Use flushSync in React to Update the Screen Immediately After setState
Right after you update state in React, t ...

React useRef vs useState: Choosing by Render Count
Changing a useState value makes React re ...

How to Build a Swipe-to-Delete List in React
I built a list where dragging a row to t ...

How to Extract a React Custom Hook and Test It with renderHook
Steps for extracting a custom hook from ...

Draggable Sticky Notes in React Without a Library
I built a feature that moves sticky note ...
