Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Server Components vs Client Components: Where the use client Boundary Actually Lands

The directive marks a module graph, not a component. Serializable props, the children pattern, context providers, and the hydration mismatches that follow.

~4 min readNext.js
#Next.js#React#Server Components#Client Components
3D illustration of a server rack with async components beside a browser window with client components and a boundary line

Quick Summary

Every component in the App Router is a Server Component unless the file starts with "use client". Server Components render on the server, can be async, can read the database directly, and send only their rendered output to the browser — their code never ships. Client Components are the ones with state, effects, event handlers, and browser APIs, and they ship JavaScript.

The boundary is a module boundary, not a component boundary. "use client" at the top of a file marks that file and everything it imports as client code. Imports point one way only: a Client Component cannot import a Server Component, but a Server Component can render a Client Component and pass it props.

Props crossing the boundary must be serializable: strings, numbers, booleans, arrays, plain objects, Date, Map, Set, and Server Actions (functions marked "use server"). Functions, class instances, and Symbols are not. The children pattern — a Server Component rendering a Client Component with server-rendered children — is the standard way to keep large trees on the server while wrapping them in interactivity.

Basic Syntax & Core Signatures

tsx
// app/products/page.tsx — Server Component: no directive, async allowed import { db } from "@/lib/db"; import { AddToCart } from "./add-to-cart"; export default async function Products() { const products = await db.product.findMany({ take: 20 }); return ( <ul> {products.map((p) => ( <li key={p.id}> <span>{p.name}</span> {/* Passing a Server Action as a prop keeps the boundary small */} <AddToCart id={p.id} price={p.price} /> </li> ))} </ul> ); }
tsx
// app/products/add-to-cart.tsx — Client Component "use client"; import { useState, useTransition } from "react"; import { addItem } from "@/app/actions"; export function AddToCart({ id, price }: { id: string; price: number }) { const [qty, setQty] = useState(1); const [pending, startTransition] = useTransition(); return ( <form action={() => startTransition(() => addItem(id, qty))} onSubmit={(e) => e.preventDefault()} > <button onClick={() => setQty((q) => q + 1)} type="button"> {qty} × ${price} </button> <button disabled={pending}>Add</button> </form> ); }
tsx
// app/actions.ts — a Server Action, callable from client code "use server"; import { revalidateTag } from "next/cache"; import { auth } from "@/lib/auth"; export async function addItem(id: string, qty: number) { const session = await auth(); // runs on the server only if (!session) throw new Error("unauthorized"); await db.cart.upsert({ userId: session.userId, productId: id, qty }); revalidateTag(`cart:${session.userId}`); }
tsx
// The children pattern: server content inside a client wrapper // layout.tsx (server) <Modal> {/* client: has open state */} <ProductTable /> {/* server: async, reads the DB */} </Modal>

Key Comparison Table

CapabilityServer ComponentClient Component
async component bodyYesNo
useState, useEffect, useRefNoYes
Event handlers (onClick)NoYes
Direct DB / filesystem accessYesNo
cookies(), headers()YesNo
Ships JavaScript to the browserNo (only HTML/RSC payload)Yes
Can import a Server ComponentYesNo (use children instead)
Secrets, API keys in the codeSafeExposed
Value across the boundaryAllowed
String, number, boolean, null, undefinedYes
Plain object, array, Map, Set, DateYes
Server Action referenceYes
Function declared in a Server ComponentNo
Class instance, Symbol, WeakMapNo
PromiseYes (Next.js resolves it)

Practical Edge Cases & Deep Dives

1. "use client" is transitive, and it spreads

text
app/page.tsx (server) └ imports Button.tsx ("use client") └ imports utils.ts -> becomes client code └ imports Chart.tsx -> becomes client code, even if it has no hooks

Marking one file client marks its whole import graph. A heavy charting library pulled in by a single interactive button now ships to every visitor of that route. The fix is to keep the client leaf small: move the interactivity into the smallest component that needs it, and pass server-rendered content in as children.

tsx
// Bad: the whole page becomes client code "use client"; import { Chart } from "recharts"; // Good: only the toggle is client; the chart stays server-rendered

2. Props must be serializable — and functions are the usual violation

tsx
// Server Component <ClientChart format={(n) => `$${n}`} /> // Error: Functions cannot be passed

The serializer rejects functions because there is nothing to send across. Server Actions are the exception: a function defined in a "use server" module or marked inline with "use server" is transmitted as a reference, and that is why <form action={serverAction}> works. For formatting, pass a plain string flag (format="currency") and let the client component pick a formatter, or render the formatted value on the server and pass the string.

3. Context, providers, and the client boundary

React context is client-only. A theme or query provider must live in a Client Component, and a Server Component can render it as a wrapper:

tsx
// app/providers.tsx "use client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; const client = new QueryClient(); export function Providers({ children }: { children: React.ReactNode }) { return <QueryClientProvider client={client}>{children}</QueryClientProvider>; } // app/layout.tsx (server) <Providers>{children}</Providers>

The children are already-rendered server output, so wrapping them does not pull the tree into client code. Creating the QueryClient at module scope is a common production bug on the server — a single shared client across requests. Create it inside the component with useState(() => new QueryClient()).

4. Hydration errors: server and client must produce the same markup

A Server Component rendering new Date().toLocaleString() and a Client Component rendering the same expression in its first render disagree, and React 19 reports a hydration mismatch. The reliable patterns are to render time-dependent output in a useEffect, to pass a server-computed timestamp as a prop, or to wrap the client part in suppressHydrationWarning when a small difference is acceptable (a clock, a relative time label).

tsx
"use client"; const [now, setNow] = useState<string | null>(null); useEffect(() => setNow(new Date().toLocaleString()), []); return <span>{now ?? "—"}</span>;

5. Reading cookies and headers makes a route dynamic

tsx
import { cookies } from "next/headers"; export default async function Page() { const theme = (await cookies()).get("theme")?.value ?? "light"; return <div data-theme={theme}>…</div>; }

cookies() and headers() in Next.js 15 are async and opt the route into dynamic rendering. That is correct for a personalised page and disastrous for a cached marketing page. When only one small part needs the cookie, put it in a nested component under <Suspense> so the rest can still be prerendered, or read the value in middleware and expose it as a request header the page can consume deliberately.

Common Runtime & Configuration Mistakes

SymptomCauseFix
Functions cannot be passed directly to Client ComponentsHandler passed as a propUse a Server Action or move the handler into the client component
useState only works in a Client ComponentMissing "use client"Add the directive at the top of the file
Bundle size jumpedA client file imports a heavy moduleSplit the client leaf
Hydration mismatchDate/Math.random() rendered on both sidesRender in useEffect, or pass from the server
cookies() returns a Promise errorNot awaited (Next.js 15+)await cookies()
Secrets exposed in the bundle"use client" file reading envMove to a Server Component or a route handler
async component inside a client componentClient components cannot be asyncFetch in the parent and pass data
Context is undefined in a Server ComponentContext is client-onlyWrap with a client provider
Page unexpectedly dynamicheaders(), cookies(), or searchParamsMove behind Suspense or accept it
Server Action called from an effect loopsrevalidate on every renderCall from an event or a form action

Server and client are two runtimes with a serializer between them. Decide per component which side it belongs on, keep the client leaf as small as it can be, and treat every prop as something that must survive JSON.

Try matching browser tools

All tools

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

All Next.js guides

More in Next.js

All Next.js guides

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