React Server Components Explained
You open the bundle analyzer on a React app and find that a product page, which is mostly text and images, pulls in a Markdown parser, a date library, and a pile of fetch-and-loading-state code. None of that needs to run in the browser. It's there because in classic React every component ships its JavaScript to the client, whether it's interactive or not.
React Server Components (RSC) are React's answer to that. They became stable with React 19 and are the default in the Next.js App Router. In this post I'll cover how they actually work, how they differ from plain SSR, the rules that trip people up, and the errors you'll see when you break them.
A server component runs on the server, sends its rendered output to the browser, and its code never lands in the client bundle. Only components marked 'use client' ship JavaScript and hydrate. Less code to download, parse, and run on the user's device.
What Are React Server Components?
The idea is simple: some components run only on the server. Because of that, they can read from a database, the filesystem, or environment variables directly, with no API layer in between. Their code is never bundled into client-side JavaScript.
That's not the same thing as Server-Side Rendering (SSR), which React has had for years, and mixing the two up causes most of the confusion:
| Feature | Server Components (RSC) | Client Components | Traditional SSR |
|---|---|---|---|
| Where does it run? | Server only | Browser (+ hydration) | Server + Browser |
| JS sent to client? | No | Yes | Yes (full component) |
| useState / useEffect? | Not allowed | Yes | Yes (after hydration) |
| Direct DB access? | Yes | No (needs API) | getServerSideProps only |
| Browser APIs? | No | Yes | After hydration only |
| Re-renders on interaction? | No | Yes | No (requires navigation) |
The point is that most UI doesn't need interactivity. Navigation bars, product listings, blog posts, read-only dashboards: they fetch data and render markup. With RSC they cost nothing in client JavaScript.
How React Server Components Work
Here's roughly what happens when a user requests a page:
RSC sends a special payload (not HTML) that the client runtime uses to construct the UI tree
The RSC payload is a compact, streamable description of the component tree. It contains references to client components, so the runtime knows where to drop them in and hydrate them. That's why server and client components can be interleaved in the same tree without losing interactivity.
If you want to see it, open the Network tab and click a <Link> in an App Router app. You'll see a request with an RSC: 1 header (or an _rsc= query param) and a response that looks like line-based JSON with references like $L1. That's the payload. It's useful when you're debugging why a page shows stale data after navigation.
The RSC Protocol vs. Traditional SSR
Traditional SSR renders a complete HTML string on the server and sends it to the browser. The browser then downloads and runs the JavaScript for every component to "hydrate" the page (attach event listeners). Purely static components still add to the bundle.
With RSC, server components are serialized into the payload and never appear in the client bundle. Only client components (the ones under a 'use client' boundary) hydrate. So RSC and SSR aren't competing options. Next.js uses both: SSR produces the first HTML, RSC decides which code ever reaches the browser.
Server vs. Client Components in Practice
In Next.js App Router, all components are server components by default. You opt into client-side interactivity with the 'use client' directive.
Server components can await data directly. No useEffect, no loading state, no API route:
// app/products/page.tsx
// No 'use client', so this is a Server Component by default
import { db } from '@/lib/database'
export default async function ProductsPage() {
// Direct database access, running on the server
const products = await db.product.findMany({
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 20,
})
return (
<main>
<h1>Products</h1>
<ul>
{products.map((p) => (
<li key={p.id}>
<h2>{p.name}</h2>
<p>${p.price}</p>
</li>
))}
</ul>
</main>
)
}
// This component ships ZERO JavaScript to the browser.
// The database query never leaks to the client.
Add 'use client' at the top of any file that needs interactivity:
// components/AddToCartButton.tsx
'use client' // ← This boundary activates client features
import { useState } from 'react'
import { addToCart } from '@/lib/cart-actions'
interface Props {
productId: string
productName: string
}
export function AddToCartButton({ productId, productName }: Props) {
const [loading, setLoading] = useState(false)
const [added, setAdded] = useState(false)
async function handleClick() {
setLoading(true)
await addToCart(productId)
setLoading(false)
setAdded(true)
}
return (
<button
onClick={handleClick}
disabled={loading || added}
>
{added ? '✓ Added!' : loading ? 'Adding...' : `Add ${productName} to Cart`}
</button>
)
}
// Only this component (and its imports) go into the JS bundle.
Server and client components compose naturally. Pass server-fetched data down as props:
// app/products/[id]/page.tsx (Server Component)
import { db } from '@/lib/database'
import { AddToCartButton } from '@/components/AddToCartButton'
import { ProductReviews } from '@/components/ProductReviews'
export default async function ProductPage({
params,
}: {
params: { id: string }
}) {
// Server-side data fetch: a direct DB call
const product = await db.product.findUniqueOrThrow({
where: { id: params.id },
include: { reviews: true, category: true },
})
return (
<div>
{/* Static server-rendered content, zero JS */}
<h1>{product.name}</h1>
<p>{product.description}</p>
<span>Category: {product.category.name}</span>
{/* Client component receives serializable props */}
<AddToCartButton
productId={product.id}
productName={product.name}
/>
{/* Another client component for interactive reviews */}
<ProductReviews
initialReviews={product.reviews}
productId={product.id}
/>
</div>
)
}
// Rule: Server components CAN render client components.
// Client components CANNOT render server components (directly).
Parallel data fetching with Promise.all and React's cache():
// lib/data.ts
import { cache } from 'react'
import { db } from '@/lib/database'
// cache() deduplicates requests in the same render tree
export const getUser = cache(async (userId: string) => {
return db.user.findUnique({ where: { id: userId } })
})
export const getProductsByUser = cache(async (userId: string) => {
return db.product.findMany({ where: { userId } })
})
// app/dashboard/page.tsx
import { getUser, getProductsByUser } from '@/lib/data'
export default async function DashboardPage({
params,
}: {
params: { userId: string }
}) {
// Promise.all runs these in PARALLEL, so there's no waterfall
const [user, products] = await Promise.all([
getUser(params.userId),
getProductsByUser(params.userId),
])
return (
<div>
<h1>Welcome, {user?.name}</h1>
<p>You have {products.length} products.</p>
</div>
)
}
// If getUser() is called again in a child component,
// React's cache() returns the cached result. No extra DB query.
Setting Up Next.js App Router
The App Router has supported server components since Next.js 13. A minimal setup looks like this.
Create a New Next.js Project
Use create-next-app with the App Router (the default since Next.js 13.4).
npx create-next-app@latest my-rsc-app \
--typescript \
--tailwind \
--app \
--src-dir
cd my-rsc-app
npm run dev
Understand the App Directory Structure
The app/ directory uses a file-system router where each folder represents a route segment.
app/
├── layout.tsx # Root layout (Server Component)
├── page.tsx # Home page (Server Component)
├── globals.css
├── products/
│ ├── page.tsx # /products route (Server Component)
│ └── [id]/
│ └── page.tsx # /products/[id] (Server Component)
├── dashboard/
│ ├── layout.tsx # Dashboard layout with auth
│ └── page.tsx # Dashboard page
components/
├── ProductCard.tsx # Server Component (no directive)
├── CartButton.tsx # Client Component ('use client')
├── SearchBar.tsx # Client Component (needs input events)
└── Header.tsx # Server Component (static nav)
lib/
├── database.ts # Prisma / DB client
└── data.ts # Cached data-fetching functions
Configure Database Access
Install Prisma or another ORM to query your database directly from server components.
import { PrismaClient } from '@prisma/client'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
export const db =
globalForPrisma.prisma ??
new PrismaClient({
log: ['query'],
})
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = db
// Usage in any Server Component:
// import { db } from '@/lib/database'
// const users = await db.user.findMany()
The globalThis trick matters in development. Without it, every hot reload creates a new PrismaClient, and after a while you'll hit Postgres's "too many clients already" error. It's also worth adding import 'server-only' at the top of files like this: if a client component ever imports it by accident, the build fails instead of quietly trying to bundle your DB client for the browser.
Use Server Actions for Mutations
Server Actions run server-side code from a form submission or a client event, without you writing an API route.
'use server' // Marks this module as server-only
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { db } from '@/lib/database'
import { z } from 'zod'
const CreateProductSchema = z.object({
name: z.string().min(1).max(200),
price: z.coerce.number().positive(),
description: z.string().min(10),
})
export async function createProduct(formData: FormData) {
const parsed = CreateProductSchema.safeParse({
name: formData.get('name'),
price: formData.get('price'),
description: formData.get('description'),
})
if (!parsed.success) {
return { error: parsed.error.flatten() }
}
const product = await db.product.create({
data: parsed.data,
})
// Invalidate the products page cache
revalidatePath('/products')
// Redirect to the new product
redirect(`/products/${product.id}`)
}
A <form action={createProduct}> rendered by a server component submits as a normal HTML form if JavaScript hasn't loaded yet. Once it has, React submits it with fetch and updates the page without a full reload. One caveat: a Server Action is a public POST endpoint. Validate input (as the Zod schema does above) and check auth inside the action itself, not just in the page that renders the form.
Performance Benefits in Practice
How much you save depends on how much of your UI is static. A content-heavy site gains a lot; a highly interactive editor gains little. Here's what changes structurally:
The less interactive your pages are, the more client JavaScript RSC removes
Heavy Libraries Become Free
This is the benefit I notice most day to day. Packages you only need for rendering can stay on the server. A Markdown renderer is the classic example:
// Traditional React (client-side): marked ships to the browser
'use client'
import { marked } from 'marked' // ends up in your JS bundle
import { useEffect, useState } from 'react'
export function BlogPost({ mdContent }: { mdContent: string }) {
const [html, setHtml] = useState('')
useEffect(() => {
setHtml(marked(mdContent))
}, [mdContent])
return <article dangerouslySetInnerHTML={{ __html: html }} />
}
// Server Component: NO 'use client' directive
import { marked } from 'marked' // runs on server, never bundled
import DOMPurify from 'isomorphic-dompurify'
export async function BlogPost({ slug }: { slug: string }) {
// Fetch from DB on the server
const post = await db.post.findUnique({ where: { slug } })
const rawHtml = marked(post.content)
const safeHtml = DOMPurify.sanitize(rawHtml)
return (
<article
className="prose"
dangerouslySetInnerHTML={{ __html: safeHtml }}
/>
)
}
// Neither marked nor DOMPurify appears in the client bundle.
Rules, Constraints, and Common Pitfalls
Some of the React you already know doesn't work in server components, and Next.js tells you with build or runtime errors. The most common one you'll see is:
You're importing a component that needs useState. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
The fix is almost always to add 'use client' to the file that uses the hook, not to the page that imports it.
What Server Components Cannot Do
| Forbidden in Server Components | Why | Solution |
|---|---|---|
useState / useReducer |
No client state on server | Move to a Client Component |
useEffect / useLayoutEffect |
No browser lifecycle on server | Fetch data directly (async/await) |
Event handlers (onClick, onChange) |
No DOM events on server | Pass down to Client Components |
Browser APIs (window, document, localStorage) |
Don't exist in Node.js | Use in Client Components only |
Context (React.createContext consumer side) |
No per-request state in tree | Pass data as props; use context in client subtree |
| Importing Client-only packages | e.g., packages using window internally |
Import them from a Client Component (use next/dynamic with ssr: false there, since it isn't allowed in Server Components) |
'use client' doesn't mean "this component runs only in the browser." Client components are still rendered to HTML on the server during SSR. It marks the boundary where the server-to-client handoff happens, and everything imported below it goes into the client bundle. Put it as far down the tree as you can, on the button or the dropdown, not on the whole page.
Props Must Be Serializable
Props from a server component to a client component travel inside the RSC payload, so React has to be able to serialize them. That's a bit wider than plain JSON (React 19 handles Date, Map, Set and promises), but functions and class instances won't make it. Pass a regular function and you get Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".
// ✅ VALID: plain values serialize fine
<ClientComponent
id="abc-123"
count={42}
product={{ name: 'Widget', price: 9.99 }}
tags={['electronics', 'sale']}
createdAt={new Date().toISOString()} // Dates as strings ✓
/>
// ❌ RISKY: check each one before you rely on it
<ClientComponent
fn={myFunction} // Fails: functions can't be serialized
mapObj={new Map()} // OK in React 19, but strings/arrays are safer
setObj={new Set()} // OK in React 19, but strings/arrays are safer
date={new Date()} // OK in React 19; older setups needed ISO strings
classInstance={new MyClass()} // Fails: class instances can't be serialized
/>
// ✅ Pass functions via Server Actions instead
import { myServerAction } from './actions'
<ClientComponent action={myServerAction} />
// Server Actions ARE serializable: they're RPC references
The "Children as a Slot" Pattern
Since Client Components can't import Server Components directly, use the children prop to pass server-rendered content into a client wrapper:
// components/Modal.tsx: Client Component (needs useState)
'use client'
import { useState } from 'react'
export function Modal({ children }: { children: React.ReactNode }) {
const [open, setOpen] = useState(false)
return (
<>
<button onClick={() => setOpen(true)}>Open</button>
{open && (
<div className="modal-overlay" onClick={() => setOpen(false)}>
<div className="modal-content" onClick={(e) => e.stopPropagation()}>
{children} {/* ← Server-rendered content goes here */}
</div>
</div>
)}
</>
)
}
// app/page.tsx: Server Component uses Modal with server-fetched content
import { Modal } from '@/components/Modal'
import { UserDetails } from '@/components/UserDetails' // Server Component
export default async function Page() {
const user = await db.user.findUnique({ where: { id: '123' } })
return (
<Modal>
{/* This is a Server Component passed as children */}
<UserDetails user={user} />
</Modal>
)
}
// Modal is a Client Component, but its children (UserDetails)
// are still server-rendered, and their code stays off the client.
When to Use Server vs. Client Components
My rule: start with a server component and only switch when something forces you to.
Use Server Components when...
- Fetching data from a database, CMS, or external API: keep it on the server.
- Reading environment variables or secrets: they never reach the client.
- Rendering large, mostly static content like blog posts, product descriptions, or docs.
- Using heavy npm packages such as parsers, formatters, or crypto libraries.
- Building navigation, headers, footers that don't respond to input.
- Doing access control: check auth on the server before rendering anything.
Use Client Components when...
- Adding event listeners: onClick, onChange, onSubmit, and so on.
- Using React hooks like useState, useEffect, useRef, useMemo.
- Touching browser APIs: localStorage, sessionStorage, navigator, window.
- Building interactive UI such as modals, dropdowns, accordions, carousels.
- Using client-side libraries like chart.js, Mapbox, or Framer Motion.
- Handling real-time updates over WebSockets, SSE, or polling.
When I'd use RSC (and when I wouldn't)
For a new Next.js project with a lot of read-heavy pages (marketing sites, blogs, e-commerce catalogs, admin screens that mostly display data), I'd use server components by default. That's where the bundle savings and the simpler data fetching actually show up.
I'd think harder in a few cases:
- Highly interactive apps. A design tool, a spreadsheet, or a chat client is mostly client components anyway. You'll pay the App Router's complexity and get little bundle reduction back.
- A working SPA with a separate API. If you already have a React SPA talking to a Laravel or Express backend, rewriting it around RSC is a big migration. RSC also needs a JavaScript server at request time, so a static file host alone won't do unless you statically export.
- Teams new to the model. The server/client boundary, caching, and serialization rules take time to learn. Expect a stretch of "why is this stale?" and "why can't I pass this prop?" questions.
The mistakes I see most often: putting 'use client' on a whole layout because one button needed state, awaiting several independent fetches one after another (a server-side waterfall is still a waterfall), and assuming a Server Action is private because no page links to it. If you're trying RSC on an existing project, convert one read-only page first and compare the client bundle before and after with @next/bundle-analyzer.