React Server Components
So far every component in this course has run in the browser. React Server Components (RSC) add a second kind of component that runs only on the server — at build time or per request. Server Components can read databases and files directly, their code is never sent to the browser, and they hand the client a ready-made description of the UI.
Note: Server Components need a framework with a server and bundler integration, such as Next.js (App Router) or React Router in framework mode. They can't run in a plain Vite app or in these playgrounds, so this lesson explains the concept and simulates the ideas in plain JavaScript.
Two kinds of components
| Server Component (default in RSC frameworks) | Client Component ('use client') |
|
|---|---|---|
| Runs | on the server only | on the server for the first HTML, then in the browser |
Can be async |
✅ await db.query(…) directly |
❌ (use use() or effects) |
| Access secrets, files, databases | ✅ | ❌ |
State and effects (useState, useEffect) |
❌ | ✅ |
Event handlers (onClick) |
❌ | ✅ |
| JavaScript sent to the browser | none | its code and dependencies |
A Server Component looks like an ordinary component, except it can be async:
// app/products/page.jsx — a Server Component (no directive needed)
import { db } from './db.js';
import AddToCartButton from './AddToCartButton.jsx';
export default async function ProductsPage() {
const products = await db.products.findMany({ orderBy: { name: 'asc' } });
return (
<ul>
{products.map((p) => (
<li key={p.id}>
{p.name} — ${p.price}
<AddToCartButton productId={p.id} />
</li>
))}
</ul>
);
}Interactive parts live in Client Components, marked with the 'use client' directive at the top of the file:
// app/products/AddToCartButton.jsx
'use client';
import { useState } from 'react';
export default function AddToCartButton({ productId }) {
const [added, setAdded] = useState(false);
return <button onClick={() => setAdded(true)}>{added ? 'Added ✓' : 'Add to cart'}</button>;
}'use client' marks a boundary: this file and everything it imports become part of the browser bundle.
What travels over the network?
The server runs the Server Components and sends the result — a serialized tree of elements — to the browser. Client Components appear in that tree only as references ("render AddToCartButton here with these props"). Let's simulate the idea:
// --- "server" ---------------------------------------------------------
const database = [
{ id: 1, name: 'Green tea', price: 4 },
{ id: 2, name: 'Mooncake', price: 7 },
];
async function ProductsPage() {
const products = await Promise.resolve(database); // pretend: SQL query
return {
type: 'ul',
children: products.map((p) => ({
type: 'li',
children: [
`${p.name} — ${p.price} `,
{ type: '$client:AddToCartButton', props: { productId: p.id } },
],
})),
};
}
const payload = JSON.stringify(await ProductsPage());
console.log('Sent to browser:', payload.length, 'characters');
console.log(payload.slice(0, 95) + '…');
// --- "browser" --------------------------------------------------------
const clientComponents = {
AddToCartButton: ({ productId }) => `[Add #${productId} to cart]`,
};
function render(node) {
if (typeof node === 'string') return node;
if (node.type.startsWith('$client:')) return clientComponents[node.type.slice(8)](node.props);
return `<${node.type}>${node.children.map(render).join('')}</${node.type}>`;
}
console.log(render(JSON.parse(payload)));Sent to browser: 233 characters
{"type":"ul","children":[{"type":"li","children":["Green tea — $4 ",{"type":"$client:AddToCartB…
<ul><li>Green tea — $4 [Add #1 to cart]</li><li>Mooncake — $7 [Add #2 to cart]</li></ul>
The browser never received the database code or the query — only data and a pointer to the client component. Real RSC payloads use a compact streaming format, but the principle is the same.
Props must be serializable
Because Server Component output crosses the network, props passed from a Server Component to a Client Component must be serializable:
| Allowed | Not allowed |
|---|---|
strings, numbers, booleans, null |
functions (except Server Functions) |
| plain objects and arrays | class instances |
Date, Map, Set, BigInt |
symbols created at runtime |
JSX elements (including Server Components as children) |
DOM nodes |
Promises (read on the client with use) |
const props = { id: 7, title: 'Mooncake', onBuy: () => {} };
function checkSerializable(obj) {
for (const [key, value] of Object.entries(obj)) {
if (typeof value === 'function') console.log(`✗ ${key}: functions can't be sent to the client`);
else console.log(`✓ ${key}: ${JSON.stringify(value)}`);
}
}
checkSerializable(props);✓ id: 7
✓ title: "Mooncake"
✗ onBuy: functions can't be sent to the client
Composition across the boundary
A Client Component can't import a Server Component, but it can receive one as children — the server renders it first and passes the result in:
// Server Component
import Tabs from './Tabs.jsx'; // 'use client'
import ProductList from './ProductList.jsx'; // server
export default function Page() {
return (
<Tabs>
<ProductList /> {/* rendered on the server, slotted into the client Tabs */}
</Tabs>
);
}The client side in practice
Everything interactive is still regular React — exactly what you've learned. This is what the AddToCartButton from above does once it reaches the browser:
import { useState } from 'react';
// In an RSC app this file would start with 'use client'
function AddToCartButton({ productId }) {
const [added, setAdded] = useState(false);
return (
<button onClick={() => setAdded(!added)} style={{ marginLeft: 8 }}>
{added ? 'Added ✓' : 'Add to cart'}
</button>
);
}
// Pretend this list arrived pre-rendered from the server
const fromServer = [
{ id: 1, name: 'Green tea', price: 4 },
{ id: 2, name: 'Mooncake', price: 7 },
];
export default function App() {
return (
<ul>
{fromServer.map((p) => (
<li key={p.id}>{p.name} — ${p.price}<AddToCartButton productId={p.id} /></li>
))}
</ul>
);
}Server Functions
A function marked 'use server' can be called from the client — React sends a request behind the scenes. Combined with form Actions:
// actions.js
'use server';
export async function addComment(formData) {
await db.comments.create({ text: formData.get('text') });
}
// Comments.jsx (Server Component)
import { addComment } from './actions.js';
export default function Comments() {
return (
<form action={addComment}>
<input name="text" />
<button>Post</button>
</form>
);
}Watch out:
'use server'marks Server Functions, not Server Components. Server Components need no directive at all.
Benefits and trade-offs
- Smaller bundles: heavy libraries used only for rendering (markdown parsers, date libraries) stay on the server.
- Direct data access: no separate API layer just to feed your own UI.
- Streaming: combined with Suspense, the server sends parts of the page as they become ready.
- Trade-off: you need a server-capable framework, and you must think about which side each component runs on.
Test yourself
Which of these can a Server Component do?
- Use useState
- Attach an onClick handler
- Await a database query directly
- Read window.innerWidth
What does the 'use client' directive do?
- Makes a component run only on the server
- Marks a file (and its imports) as part of the browser bundle
- Disables server rendering for the whole app
- Creates a Server Function
Why can't a Server Component pass a regular function as a prop to a Client Component?
- Functions are too large
- Props must be serialized to travel to the browser, and functions can't be
- Client Components can't receive props
- It's allowed