React Server Components (RSC): Architecture, Mental Model, and Patterns
React Server Components (RSC): Render data-heavy components exclusively on the server to dramatically shrink client JavaScript bundles.
In traditional Single-Page Applications (SPAs) and standard Server-Side Rendering (SSR), every component in your application codebase ultimately travels to the browser as JavaScript. Even if a component merely renders static typography, parses markdown, or formats timestamps with a heavy date library, the client bundle must still download, parse, and execute that code before the UI becomes interactive.
React Server Components (RSC) introduce a fundamental split in the component execution model. Instead of treating every file as browser-bound code, React divides your component tree across two distinct runtimes:
- **Server Components (Default):** Execute exclusively on the backend. Their source code, imports, and dependencies never leave the server, resulting in a 0 kB client bundle footprint.
- **Client Components (Opt-in via 'use client'):** Hydrate on the client to provide interactive capabilities like event handlers, hooks, and browser API integrations.
## 1. Demystifying the Difference: SSR vs. RSC
A common point of confusion is conflating Server Components with traditional Server-Side Rendering. They address fundamentally different problems and are engineered to complement each other.
```text
[ Classic SSR (Pages Router / Traditional Frameworks) ]
Server: Executes component tree ──► Generates raw HTML string
Network: Ships initial HTML + 100% of the component JavaScript
Client: Downloads entire JS bundle ──► Hydrates every single component on screen
```
```text
[ React Server Components Architecture ]
Server: Executes Server Components ──► Queries DB/APIs directly
Renders to a compact, non-HTML stream (RSC Flight Data)
Network: Ships fast initial HTML + ONLY Client Component JavaScript bundles
Client: Merges RSC stream into Virtual DOM ──► Hydrates ONLY Client Components
```
| Dimension | Traditional Server-Side Rendering (SSR) | React Server Components (RSC) |
| --- | --- | --- |
| Execution Phase | Runs once on the server, then runs a second time on the client during hydration. | Runs only on the server. Never re-executes in the browser. |
| Bundle Impact | Heavy. Every third-party library imported ships to the browser bundle. | Zero bundle footprint. Server libraries never touch the client payload. |
| Interactivity & State | Can use state and effects once hydrated on the client. | Cannot use useState, useEffect, or event listeners (onClick). |
| Data Fetching | Relies on specialized lifecycle hooks (getServerSideProps, route loaders). | Components are native async/await functions fetching data inline. |
| Refetching State | Refreshing data often resets client UI state unless manually synchronized. | Server trees can refetch and stream updates without resetting active client DOM state. |
## 2. The 0 kB Bundle Advantage: Offloading Heavy Libraries
In a client-heavy application, dependencies like markdown compilers, syntax highlighters, and data sanitizers rapidly inflate bundle size. With RSC, heavy parsing happens once on the server, and the library code is discarded before the client receives the payload.
```ts
// src/components/BlogPost.tsx (Server Component by default)
// NONE of these imports are sent to the client bundle!
import { marked } from 'marked'; // ~35 kB saved
import sanitizeHtml from 'sanitize-html'; // ~60 kB saved
import db from '@/lib/db'; // Direct database access!
interface BlogPostProps {
slug: string;
}
// Direct async component: no useEffect, loaders, or fetch boilerplate
export default async function BlogPost({ slug }: BlogPostProps) {
// Query your database directly behind your private VPC/firewall
const post = await db.post.findUnique({
where: { slug },
});
if (!post) {
return
);
}
```
The browser receives only the resulting HTML tags and CSS—saving roughly ~100 kB of JavaScript execution cost.
## 3. The 'use client' Directive: Defining Module Boundaries
The 'use client' declaration at the top of a file does not mean "render this only on the client." Instead, it defines a boundary cut-point between the server-only module graph and the client-hydrated module graph.
Components imported above or outside 'use client' are Server Components.
Components marked with 'use client' are Client Components—they still render to static HTML on the server during the initial page load for fast paint times, but their JavaScript code is shipped over the wire to hydrate interactive behavior in the browser.
```text
[ Root Layout (Server) ]
│
▼
[ ProductPage (Server) ] ── (Direct DB Fetch: { name, price, stock })
│
├──────────────────────────────┐
▼ ▼
[ ProductDetails (Server) ] [ AddToCartButton (Client) ]
• Pure presentation • 'use client' boundary
• 0 kB client JS • useState(quantity)
• Reads DB data directly • onClick={handleAddToCart}
• Bundled & shipped to browser
```
### Implementing the Client Boundary
```ts
// src/components/AddToCartButton.tsx
'use client'; // ◄── Marks the boundary: shipped to browser for hydration
import { useState } from 'react';
interface CartProps {
productId: string;
inStock: boolean;
}
export function AddToCartButton({ productId, inStock }: CartProps) {
const [quantity, setQuantity] = useState(1);
const [isPending, setIsPending] = useState(false);
const handleAdd = async () => {
setIsPending(true);
await fetch('/api/cart', {
method: 'POST',
body: JSON.stringify({ productId, quantity }),
});
setIsPending(false);
};
return (
);
}
```
Once a module has the 'use client' directive, everything imported downstream into that file is pulled into the client bundle, stripping away the server component benefits.
- **The Fix:** Composition via Component Slots (children)
To nest a Server Component inside a Client Component (such as a modal, an animated carousel, or an expandable drawer), treat the Client Component as an outer layout shell and pass the Server Component via the children prop:
```ts
// src/components/CollapsibleSection.tsx (Client Component)
'use client';
import { useState, type ReactNode } from 'react';
export function CollapsibleSection({ children }: { children: ReactNode }) {
const [isOpen, setIsOpen] = useState(true);
return (
{/* Server Component rendered here without entering the client bundle */}
{isOpen &&
);
}
```
```ts
// src/app/dashboard/page.tsx (Server Component)
import { CollapsibleSection } from '@/components/CollapsibleSection';
import HeavyServerReport from '@/components/HeavyServerReport';
export default function DashboardPage() {
return (
);
}
[ DashboardPage (Server Component) ]
│
▼
[ CollapsibleSection (Client Component) ]
│ (passes as children slot)
▼
[ HeavyServerReport (Server Component) ]
```
HeavyServerReport executes strictly on the backend. Its evaluated UI output is passed into the children slot of CollapsibleSection without pulling its code or dependencies into the browser.
## 5. Under the Hood: The RSC Flight Protocol
When navigating between pages in an RSC application, the browser does not request a full HTML document reload, nor does it receive plain JSON data.
Instead, the server sends a streaming, text-based serialization format called the RSC Flight Stream:
- Plaintext
- M1:\{"id":"./src/components/AddToCartButton.tsx","chunks":["client-cart.js"],"name":"AddToCartButton"\}
- J0:["$","article",null,\{"className":"prose","children":[["$","h1",null,\{"children":"RSC Deep Dive"\}],["","L1",null,\{"productId":"prod_987"\}]]\}]
### How the Flight Stream Works
- **Module References (M lines):** Declare which Client Component chunks the browser needs to load for hydration.
- **Virtual DOM Descriptors (J lines):** Outline the component tree structure. Notice that Server Components (article, h1) are already resolved into pure element descriptors.
- **Preserving Client State:** When navigating or revalidating server data, React reconciles this flight stream against the existing client Fiber tree. Input focus, typed form text, and local client state remain completely intact during re-renders.
## 6. Serialization Boundaries: Passing Props from Server to Client
Because props passed from Server to Client Components cross a physical network boundary (e.g., from Node.js/Edge runtimes to the client browser), all values passed must be serializable.
### Allowed as Props to Client Components
### Forbidden as Props to Client Components
### Primitives (string, number, boolean, null, undefined)
JavaScript Functions (onClick=\{() => \{\}\})
### Plain Objects (\{ id: 1, title: 'Item' \})
### Class instances with custom methods
### Plain Arrays ([1, 2, 3])
### Symbols
- **React Elements (children:** <ServerChild/>)
### Live DOM nodes or Event handlers
### Promises (unwrapped in the client via the use() hook)
Database connection instances or sockets
## 7. Decision Matrix: Server vs. Client Components
```text
Component Requirements
│
┌─────────────────────┴─────────────────────┐
▼ ▼
Needs Interactivity or Browser APIs? Needs Direct Backend Data Access?
- useState / useReducer • Direct database or ORM queries
- useEffect / useLayoutEffect • Private backend credentials / API keys
- Window, localStorage, navigator • Heavy file / text parsing libraries
- Custom event listeners (onClick, onInput) • Zero client bundle impact
│ │
▼ ▼
CLIENT COMPONENT SERVER COMPONENT
('use client') (Default)
```
- **Next.js App Router:** Leverage modern layout systems, route groups, and nested routing.
Article not found.
; } // Heavy computation runs once on the server const parsedContent = sanitizeHtml(marked.parse(post.content)); return ({post.title}
Published on {post.createdAt.toDateString()}
{/* Output is clean, static markup; client downloads zero parser JS */}
setQuantity(Number(e.target.value))}
className="w-16 border rounded p-1"
/>
);
}
```
## 4. The Interleaving Pattern: Passing Server Components as Children
A common pitfall occurs when trying to import a Server Component directly inside a Client Component file:
```ts
// ❌ WRONG: Breaks the Server Component model!
'use client';
import ServerAnalytics from './ServerAnalytics'; // ◄── Compiles into client bundle!
export function ClientWrapper() {
return (
{children}
}
