Server rendering, from the last chapter, makes content show up sooner. It doesn't make the page lighter. Every component still ships to the browser, runs again to hydrate, and drags its dependencies into the bundle, including components that only ever display data and never respond to a click.
React Server Components (RSC) fix that by splitting components into two kinds. Server Components run only on the server, never ship their code, and can read data directly. Client components are the components you've written all along: they ship, hydrate and hold state. This chapter explains the model, the boundary between the two, what can cross it, and what actually travels over the network, by building a toy version of the payload. It's the hardest conceptual topic in modern React, so we'll go slowly.
The problem: shipping code that never runs twice#
Here's a book page, written the classic way. It fetches the book in an effect, renders the description from Markdown, and has one interactive piece: a Like button.
import { useEffect, useState } from "react";
import { marked } from "marked"; // ~40 kB of parser, only to render text once
import { LikeButton } from "./LikeButton";
export function BookPage({ id }: { id: number }) {
const [book, setBook] = useState<Book | null>(null);
useEffect(() => {
fetch(`/api/books/${id}`).then((r) => r.json()).then(setBook);
}, [id]);
if (!book) return <p>Loading...</p>;
return (
<article>
<h1>{book.title}</h1>
<div dangerouslySetInnerHTML={{ __html: marked(book.description) }} />
<LikeButton bookId={id} initialLikes={book.likes} />
</article>
);
}Count what the browser pays for. The Markdown parser downloads, parses and runs just to produce text that will never change. BookPage hydrates even though nothing in it is interactive except LikeButton. There's a round trip from the browser to an API route whose only job is to feed this component. And server rendering doesn't help with any of it: SSR would render this page to HTML and then ship and hydrate all of it anyway.
What we want is to say: "this component only produces markup from data, run it where the data is, send the result, and keep its code off the client." That's a Server Component.
The model#
With Server Components, the same page looks like this:
import { marked } from "marked";
import { db } from "@/lib/db";
import { LikeButton } from "./LikeButton";
export default async function BookPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const book = await db.book.findUnique({ where: { id: Number(id) } });
return (
<article>
<h1>{book.title}</h1>
<div dangerouslySetInnerHTML={{ __html: marked(book.description) }} />
<LikeButton bookId={book.id} initialLikes={book.likes} />
</article>
);
}Read it closely, because each line says something about the model:
- Components are Server Components by default (in a framework that supports RSC, like the Next.js App Router).
BookPagehas no directive, so it runs only on the server. - They can be
asyncand await data directly: a database query, a file read, an internal service. No effect, no loading state, no API route. Client components can't be async. - Their code never ships. Neither
markednordbends up in the browser bundle. The browser receives the output: an<article>with text already in it. - They can't be interactive. No
useState, nouseEffect, no event handlers. A Server Component renders once per request (or once at build time) and is done; there's nothing to re-render in the browser. "use client"marks the other kind.LikeButtonships and runs in the browser, with state, effects and handlers, like every component in Parts 3 to 6.
- Server Components: run on the server (at build time or per request), can be async, can touch server resources, ship zero JavaScript, can't use state, effects or browser APIs.
- Client components: ship to the browser, hydrate, can be interactive. They're also rendered to HTML on the server during SSR, so "client" means "also runs in the client", not "only runs there".
One correction people need early: "use client" doesn't mean client-side rendering. On the first request, client components are still server-rendered to HTML (that's the SSR from the last chapter) and then hydrated. The directive decides where the code is available, not where it first renders.
"use client" is a cut in the module graph#
The directive doesn't mark a component. It marks a module, and with it everything that module imports. It's a boundary in the import graph: above it, modules are evaluated on the server; at and below it, modules are bundled for the browser.
The app as you wrote it: a module graph. page.tsx imports the database helper, a details component that uses a big Markdown library, and a LikeButton.
That has consequences that trip people up:
- Everything a client module imports is client code. If
LikeButton.tsximports aformatLikeshelper, that helper ships, whether or not the helper file has a directive. You only need"use client"at the entry point of a client subtree, not on every file inside it. - A client module can't import a Server Component. Importing it would make it part of the client graph, so it would become a client component (and break if it was async or used
db). - The boundary is in the module graph, not the render tree. A client component can still render a Server Component, if the Server Component is created by a server module and passed in as a prop. That's the next section.
When the server renders and reaches a client component, it doesn't run it. It can't: on the server side of the boundary, the bundler replaced that module's exports with client references, tiny objects that say "the LikeButton export of this client module". The server writes the reference and the props into its output, and the browser, which does have the code, fills it in.
Server Components as children of client components#
Suppose you want a client-side collapsible panel around server-rendered content. The panel needs state, so it's a client component. Its content is a list of reviews read from the database, which should stay on the server.
"use client";
import { useState, type ReactNode } from "react";
export function Collapsible({ title, children }: { title: string; children: ReactNode }) {
const [open, setOpen] = useState(false);
return (
<section>
<button onClick={() => setOpen(!open)}>{open ? "Hide" : "Show"} {title}</button>
{open && children}
</section>
);
}This works, and it's the most important composition pattern in RSC. Collapsible never imports Reviews. page.tsx, a server module, creates the <Reviews /> element and passes it as children. The server renders Reviews first, completely, and sends its output as the children prop. By the time Collapsible runs in the browser, children is just already-rendered UI. It can show it, hide it or move it, but it never runs Reviews.
So a parent in the render tree doesn't decide where its children run. The module that creates the element does.
The same pattern answers "my provider needs state, but I don't want my whole app to become client code". A client ThemeProvider wrapping {children} in the root layout keeps every page below it a Server Component, because the pages are passed in as children, not imported by the provider.
What can cross the boundary#
Props passed from a Server Component to a client component travel over the network, so they must be serializable. The react.dev list:
| Can cross | Can't cross |
|---|---|
Primitives: string, number, bigint, boolean, undefined, null, symbols registered with Symbol.for | Functions that aren't Server Functions (event handlers, callbacks, components) |
Arrays, Map, Set, typed arrays, ArrayBuffer, iterables of serializable values | Class instances (other than the built-ins listed) |
Date | Objects with a null prototype |
| Plain objects with serializable properties | Symbols not registered globally (Symbol("x")) |
| JSX: Server or client component elements | |
| Promises | |
Server Functions (functions marked "use server") |
Three rows deserve a second look:
- Functions don't cross, with one exception. You can't pass
onLike={() => ...}from a Server Component. There's no way to send a closure's code and scope to the browser. The exception is a Server Function, which doesn't send code at all: it sends a reference the client can use to call the server. That's the next chapter. - Promises cross. A Server Component can start a fetch without awaiting it and pass the promise down. React streams the resolved value when it's ready, and the client component reads it with
use(), suspending until then. That lets a page send its shell immediately while slow data keeps flowing. - Class instances don't. A
Userobject from your ORM fails to serialize, which is sometimes what you want (a data access layer can return class instances on purpose so they can't leak to the client), and sometimes a surprise.
import { Suspense } from "react";
import { Comments } from "./Comments";
import { getComments } from "@/lib/data";
export default function Page() {
const commentsPromise = getComments(3); // not awaited: the page doesn't block on it
return (
<Suspense fallback={<p>Loading comments...</p>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
);
}Build it: a toy RSC payload#
What actually goes over the wire for a Server Component tree? Not HTML, and not code. React serializes the rendered tree into a format called Flight, the RSC payload: a description of host elements, text, client references with their props, and placeholders for things still streaming.
Here's a simplified simulation you can run. It isn't the real Flight protocol (that's a line-based streaming format with many more types), but it has the same structure, and building it makes the rules above obvious instead of arbitrary.
The server side has three jobs. Server Components are called (and awaited). Host elements are kept as data. Client components are not called: they're written as references with their props.
import { isValidElement } from "react";
const CLIENT_REFERENCE = Symbol.for("toy.client.reference");
// What the bundler hands the server in place of a "use client" module:
// an opaque pointer to code that only exists in the browser bundle.
export function clientReference(id) {
const ref = () => {
throw new Error(`${id} is a client component. The server never runs it.`);
};
ref.$$typeof = CLIENT_REFERENCE;
ref.$$id = id;
return ref;
}
export async function renderToPayload(node) {
if (node == null || typeof node === "boolean") return null;
if (typeof node === "string" || typeof node === "number") return node;
if (Array.isArray(node)) return Promise.all(node.map(renderToPayload));
const { type, props, key } = node;
// A client component: don't run it. Describe it, with serializable props.
if (typeof type === "function" && type.$$typeof === CLIENT_REFERENCE) {
return { $client: type.$$id, ...(key != null && { key }), props: await serializeProps(props) };
}
// A Server Component: run it (it may be async) and keep rendering its output.
if (typeof type === "function") {
return renderToPayload(await type(props));
}
// A host element like <article>.
return { $el: type, ...(key != null && { key }), props: await serializeProps(props) };
}
async function serializeProps(props) {
const out = {};
for (const [name, value] of Object.entries(props)) {
if (name === "children" || isValidElement(value)) {
out[name] = await renderToPayload(value); // JSX is rendered on the server first
} else if (typeof value === "function") {
throw new Error(`Prop "${name}": functions can't be sent to the browser.`);
} else {
out[name] = value; // the real protocol also encodes Dates, Maps, promises...
}
}
return out;
}Read the payload in the console and match it against the rules:
BookDetailsandPageare gone. There's no trace of them, theirdbcall or their code. Only their output (main,article,h2with the title in it) is in the payload.LikeButtonappears as"$client": "LikeButton.js#LikeButton"with its props. Its code isn't in the payload; the browser already has it in its bundle.- Its
childrenis asmallelement, already rendered. That's server-rendered content passed into a client component, as data. - In the browser,
payloadToElementsrebuilds plain React elements, swaps the reference for the realLikeButton, and React renders the result like any other tree. The like count works because that part really is a client component.
Now break it on purpose: in server-app.js, add onLike={() => console.log("liked")} to <LikeButton>. The toy throws, for the same reason the real one does: there's no way to put a closure in the payload.
What the real payload looks like#
The real Flight format is a stream of rows. Roughly (the details are an internal format that changes between versions):
1:I["./LikeButton.js",["chunks/like-3f2a.js"],"LikeButton"]
0:["$","main",null,{"children":[["$","article",null,{"children":[["$","h2",null,{"children":"Refactoring"}],"..."]}],["$","$L1",null,{"initialLikes":12,"children":["$","small",null,{"children":"This note was rendered on the server."}]}]]}]Row 1 is an import: which client module, which bundle chunks to load, which export. Row 0 is the tree, where ["$", type, key, props] is an element and $L1 points at row 1. Because it's rows, the server can stream them: a row for a slow Suspense boundary or a promise prop can come later, referenced by id before it exists. That's how Server Components stream through Suspense.
Where the payload goes#
On the first request, a framework does two renders on the server: the RSC render (Server Components to payload, with client references) and then the SSR render (payload plus client components to HTML, the previous chapter). The HTML goes out with the payload embedded in <script> tags, so the browser can hydrate the client components without asking again. On later client-side navigations, the browser fetches only the RSC payload for the new route and React merges it into the existing tree, keeping client state where the tree didn't change.
Context in Server Components React 19.3#
Server Components can't create Context (createContext is client-only) and can't read it, since they don't run hooks. They can, however, render a Context imported from a client module. Before React 19.3 you needed a small client wrapper component just to provide it. Since 19.3 you can render <Context value> directly in a Server Component:
"use client";
import { createContext } from "react";
export const UserContext = createContext<User | null>(null);The value still crosses the boundary, so it must be serializable, and only client components below can read it. It's for contexts that exist to hand server data to the client tree. Server Components that need the same data should call the data function themselves (which cache(), next, makes cheap).
cache() and cacheSignal()#
Server Components replace prop drilling with "every component fetches what it needs". That raises an obvious problem: the layout, the header and the page all call getCurrentUser(). Three database queries for one request?
cache(fn) from react returns a memoized version of fn whose results are shared for the duration of one server request. Call it at module level, then call the memoized function from any Server Component. The first call does the work; later calls with the same arguments (compared with Object.is, so primitives work best) get the same result, or the same pending promise.
import { cache } from "react";
import { db } from "./db";
export const getUser = cache(async (id: string) => {
return db.user.findUnique({ where: { id } });
});The rules from react.dev:
- It's for Server Components only. On the client, use
useMemoor a query library. - React invalidates every
cachefor each server request. It's request-scoped deduplication, not a cross-request cache. (Next.js's"use cache", in Caching in Next.js, is the cross-request one.) - Each call to
cache()creates a new, separate cache, so define the memoized function once in a shared module, never inside a component. - Calling the memoized function outside a component runs it but doesn't read or write the cache.
You can also use it to preload: call getUser(id) without awaiting at the top of a page, so the query starts while other work renders, and the component that later awaits getUser(id) gets the in-flight promise.
cacheSignal() React 19.2 returns an AbortSignal that React aborts when the render it belongs to is finished: completed, aborted or failed. Pass it to fetches started during render so work the server no longer needs gets cancelled, or check cacheSignal()?.aborted to avoid logging cancellations as errors. Outside of rendering it returns null, and in client components it currently always returns null.
import { cache, cacheSignal } from "react";
export const getBook = cache(async (id: number) => {
const res = await fetch(`https://api.example.com/books/${id}`, { signal: cacheSignal() });
return res.json();
});Pitfalls#
Check your understanding#
Implement serializeValue(value) in serialize.js, the function a toy RSC server would run on every prop it sends to a client component. It must:
- Return primitives (
string,number,boolean,null,undefined) unchanged. - Serialize arrays and plain objects recursively.
- Encode a
Dateas{ $date: isoString }. - Encode a Server Function reference (a function with
$$typeof === SERVER_REFERENCE) as{ $server: fn.$$id }. - Throw a
TypeErrorfor any other function, and for any object that isn't a plain object (a class instance or anull-prototype object).
export const SERVER_REFERENCE = Symbol.for("toy.server.reference");
export function serializeValue(value) {
// TODO: enforce what can cross from server to client.
return value;
}None of these files has a directive except where shown. Which components are client components?
// page.tsx
import { Shell } from "./Shell";
import { Feed } from "./Feed";
export default function Page() {
return <Shell><Feed /></Shell>;
}
// Shell.tsx
"use client";
import { Sidebar } from "./Sidebar";
export function Shell({ children }) {
return <div><Sidebar />{children}</div>;
}
// Sidebar.tsx (no directive)
export function Sidebar() { return <nav>...</nav>; }
// Feed.tsx (no directive)
export async function Feed() { const posts = await db.posts(); return <ul>...</ul>; }A Server Component renders <BookCard book={...} onSelect={...} added={...} reviews={...} />, where BookCard is a client component. Which prop fails to serialize?
An interviewer asks: "What are React Server Components, and what problem do they solve that SSR doesn't?"
An interviewer asks: "A client component can't import a Server Component. So how can a Server Component appear inside a client component?"
Interview angle
Server Components are components that run only on the server, at build time or per request. They can be async and read data directly, and their code never ships: the browser receives their rendered output as the RSC payload. Client components, marked with "use client", ship, hydrate and handle interaction, and they're still server-rendered to HTML on first load. The directive cuts the module graph, so a client module and everything it imports is client code, and props crossing the boundary must be serializable. Server Components can still appear inside client components when a server module passes them in as children.
What are React Server Components?
What exactly does "use client" do?
What can you pass from a Server Component to a client component, and why those things?
How can a Server Component be rendered inside a client component?
What is the RSC payload and how does it get to the browser?
You wrapped getUser in React's cache(), but the database still sees several identical queries per request. What could be wrong?
What are the common mistakes teams make when adopting Server Components?
Recap#
- Server Components run only on the server, can be async and read data directly, and ship no JavaScript. Client components (
"use client") ship, hydrate and are interactive; they're still server-rendered to HTML on first load. "use client"cuts the module graph: the marked module and everything it imports become client code. On the server, client modules are replaced by references.- Props crossing the boundary must be serializable: primitives, plain objects, arrays, Map, Set, Date, JSX, promises and Server Functions, but not other functions or class instances.
- Server Components can be passed as children into client components; the module that creates the element decides where it runs.
- The RSC payload (Flight) is a streamed, row-based description of rendered elements and client references, used for the first render (embedded in HTML) and fetched on navigation.
- React 19.3 lets Server Components render
<Context value>imported from a client module.cache()dedupes work within one request;cacheSignal()React 19.2 aborts work when the render ends.
Sources#
- react.dev: Server Components,
'use client', Directives - react.dev:
cache,cacheSignal,use - react.dev blog: React 19, React 19.2, React 19.3 (Context rendered directly in Server Components)
- nextjs.org: Server and Client Components, Data security
- Facts checked November 24, 2026.