Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React Server Components vs Client Components: Serialization and Boundaries

use client marks a module graph, not a component. What runs where, what can cross the boundary, and how to keep interactive islands small.

~5 min readReact
#React#Server Components#Architecture
3D illustration of server-rendered RSC payloads streaming across a use client hydration boundary

Quick Summary

React Server Components run on the server and never ship to the browser. Client Components run in both places: they are pre-rendered to HTML on the server for the first paint, then hydrated in the browser where hooks, state, and event handlers work. The directive 'use client' does not mean "only in the browser" — it marks the point where the client module graph starts.

That boundary is a file boundary, not a component one. Everything imported by a 'use client' module joins the client bundle, so one 'use client' at the top of a barrel file can silently pull an entire subtree into JavaScript the user must download. The discipline is to keep the directive as low in the tree as possible, around the components that actually need interactivity.

What can cross the boundary is serializable data and server actions. Functions, class instances, and symbols cannot be passed from a server component to a client component; a plain async function marked 'use server' can, because it becomes a reference to an HTTP endpoint rather than a value in the payload.

Basic Syntax & Signature

tsx
// app/posts/[id]/page.tsx — Server Component by default (no directive). import { db } from "@/lib/db"; import { LikeButton } from "./LikeButton"; import { formatDate } from "@/lib/format"; export default async function PostPage({ params }: { params: { id: string } }) { // Direct data access: no API route, no useEffect, no fetch to yourself. const post = await db.post.findUnique({ where: { id: params.id } }); if (!post) return <p>Not found</p>; return ( <article> <h1>{post.title}</h1> <time>{formatDate(post.createdAt)}</time> <div>{post.body}</div> {/* Interactive island: the only part that ships JS. */} <LikeButton postId={post.id} initialLikes={post.likes} /> </article> ); }
tsx
// app/posts/[id]/LikeButton.tsx — Client Component. "use client"; import { useState, useTransition } from "react"; import { incrementLikes } from "./actions"; export function LikeButton({ postId, initialLikes }: { postId: string; initialLikes: number }) { const [likes, setLikes] = useState(initialLikes); const [isPending, startTransition] = useTransition(); return ( <button disabled={isPending} onClick={() => startTransition(async () => { setLikes((n) => n + 1); await incrementLikes(postId); }) } > ♥ {likes} </button> ); }
ts
// app/posts/[id]/actions.ts — Server Action, callable from the client. "use server"; import { db } from "@/lib/db"; import { revalidatePath } from "next/cache"; export async function incrementLikes(postId: string) { await db.post.update({ where: { id: postId }, data: { likes: { increment: 1 } } }); revalidatePath(`/posts/${postId}`); }

Passing server-rendered content into a client component uses children:

tsx
// Client wrapper that renders server content it cannot import. "use client"; import { useState, type ReactNode } from "react"; export function Collapsible({ children, title }: { children: ReactNode; title: string }) { const [open, setOpen] = useState(false); return ( <section> <button onClick={() => setOpen((o) => !o)}>{title}</button> {open && children} </section> ); }

Key Comparison Table

Server ComponentClient Component
DirectiveNone (default in App Router)'use client'
Runs on serverYesYes, for initial HTML
Runs in browserNoYes, after hydration
Ships JavaScriptNoYes
async componentYesNo
Hooks (useState, useEffect)NoYes
Event handlersNoYes
Browser APIs (window)NoYes
Secrets, DB, filesystemYesNo
Receives refNoYes
What crosses the boundaryAllowedWorkaround
Strings, numbers, booleans, nullYes—
Plain objects and arraysYes—
Date, Map, Set, BigInt, typed arraysYes—
PromiseYes, unwrap with use—
Server action functionYesMark the function 'use server'
Ordinary functionNoMove the logic into the client, or use an action
Class instanceNoConvert to a plain object
React element as childrenYesPass the server component as a child
Import a server componentNoPass it as children instead

Practical Edge Cases & Deep Dives

1. 'use client' is transitive down the import graph

tsx
// app/ui/index.tsx "use client"; // everything re-exported below is client export { Button } from "./Button"; export { Card } from "./Card"; export { Chart } from "./Chart"; // 180 KB of charting library, now in the bundle

A single directive in a barrel file marks every re-exported module as client code. Since the client graph is computed by imports, not by usage, a chart component imported but never rendered still ships. Keep barrel files free of directives, put 'use client' in the leaf component that truly needs interactivity, and check the bundle analyzer when a page's JavaScript grows unexpectedly.

2. Server data into a client component: serializable only

tsx
// Server export default async function Page() { const user = await db.user.findFirst(); const createdAt = new Date(); return ( <Profile user={{ id: user.id, name: user.name }} // plain object: fine createdAt={createdAt} // Date: supported by React 19 // formatter={formatName} // function: not allowed // ormClient={db} // class instance: not allowed /> ); } // Client "use client"; export function Profile({ user, createdAt }: { user: { id: string; name: string }; createdAt: Date }) { return <p>{user.name} since {createdAt.getFullYear()}</p>; }

The error when this is violated is explicit — something like "Functions cannot be passed directly to Client Components" — and the fix is to pass data, not behaviour. Formatting belongs on the server as pre-formatted strings, or on the client as an imported pure function (which is itself client code, so it ships, but a formatter is a few hundred bytes).

3. Context providers must be client components, children need not be

tsx
// app/providers.tsx "use client"; import { createContext, useState, type ReactNode } from "react"; export const ThemeContext = createContext<{ theme: string; toggle: () => void }>({ theme: "light", toggle: () => {}, }); export function Providers({ children }: { children: ReactNode }) { const [theme, setTheme] = useState("light"); const toggle = () => setTheme((t) => (t === "light" ? "dark" : "light")); return <ThemeContext.Provider value={{ theme, toggle }}>{children}</ThemeContext.Provider>; }
tsx
// app/layout.tsx — stays a server component. import { Providers } from "./providers"; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <Providers>{children}</Providers> </body> </html> ); }

children is a React element created by the server, so wrapping it in a client provider does not turn the pages into client components — the provider is an island whose children arrive pre-rendered. This is the standard way to get a theme or query client at the root without breaking server rendering.

4. Server actions from a form, with progressive enhancement

tsx
// app/contact/page.tsx — server component. import { submitContact } from "./actions"; export default function ContactPage() { return ( <form action={submitContact}> <input name="email" type="email" required /> <textarea name="message" required /> {/* Works even before hydration: the browser posts the form. */} <button type="submit">send</button> </form> ); }
ts
// app/contact/actions.ts "use server"; export async function submitContact(formData: FormData) { const email = String(formData.get("email") ?? ""); const message = String(formData.get("message") ?? ""); if (!email.includes("@") || message.length < 10) { return { ok: false, error: "Check the form." }; } await saveMessage({ email, message }); return { ok: true }; }

A server action passed to form action is a real POST endpoint, so the form submits without JavaScript and is progressively enhanced when it hydrates. The action's return value is available to useActionState on the client; its arguments must be serializable, and FormData is.

5. Fetching in the wrong place

tsx
// Wrong: a client component fetching its own page data. "use client"; function PostList() { const [posts, setPosts] = useState<Post[]>([]); useEffect(() => { fetch("/api/posts").then((r) => r.json()).then(setPosts); }, []); return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>; } // Right: fetch on the server, render on the server, ship no JS for it. async function PostListServer() { const posts = await db.post.findMany({ take: 20 }); return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>; }

The client version costs a round trip to your own API, a loading state, an error state, and the JavaScript for all three. The server version costs one query during the request and sends HTML. Interactive parts — a like button, a filter that must respond instantly — stay client components.

6. Third-party components without a client directive

tsx
// A library component that calls useState but was written for the client. // Importing it from a server component fails: "useState only works in a Client Component". import { DatePicker } from "some-date-lib"; // Fix: wrap it once, in a client module, and keep the wrapper narrow. // components/DatePickerClient.tsx "use client"; import { DatePicker } from "some-date-lib"; export function DatePickerClient(props: { value: string; onChange: (v: string) => void }) { return <DatePicker {...props} />; }

The wrapper is the boundary, not the library. Keeping it in its own file means the library is bundled once and the server page stays a server component. The same technique applies to any component that touches window, document, or a browser-only global.

Common Compilation/Runtime Mistakes

Error / symptomCauseFix
"useState only works in a Client Component"Hook used in a server componentAdd 'use client' to that file
"Functions cannot be passed directly to Client Components"Passing a callback from server to clientUse a server action, or move the handler into the client
"Event handlers cannot be passed to Client Component props"onClick in a server componentPut the interactive element in a client component
Server component imported into a client fileImport direction is one-wayPass it as children or a prop element
Entire page became client JavaScriptDirective at a barrel or layoutMove 'use client' to leaf components
window is not definedBrowser API during server render or module scopeAccess inside an effect or handler
Secret exposed in the bundleNEXT_PUBLIC_ prefix on a secretRead it only on the server
Server action called but no UI updateRevalidation missingrevalidatePath / revalidateTag
Date prop arrives as a stringA middleware or API boundary serialized it to JSONPass through RSC props, or parse on the client
Hydration mismatch after conditional server dataDifferent output on server and clientRender client-only data after mount

The mental model that prevents most mistakes: server components produce data and markup, client components produce interactivity, and the boundary between them is a file. Every time the boundary moves up, more JavaScript ships; every time it moves down, more of the app needs explicit prop plumbing. Place it per interactive island, not per page.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.