React Server Components Explained
React Server Components (RSC) render on the server and send their result to the browser, not their JavaScript. They can read databases and files directly, and they add nothing to your client bundle.
Server vs client components
- Server Components (default in frameworks like Next.js App Router): can be
async, can use secrets and server-only code, can't use state, effects or browser APIs. - Client Components (marked with
'use client'): can useuseState,useEffect, event handlers and browser APIs.
// app/products/page.jsx - a Server Component
import { db } from '@/lib/db';
import AddToCart from './AddToCart';
export default async function ProductsPage() {
const products = await db.product.findMany(); // runs only on the server
return (
<ul>
{products.map((p) => (
<li key={p.id}>
{p.name} - ₹{p.price}
<AddToCart productId={p.id} />
</li>
))}
</ul>
);
}
// app/products/AddToCart.jsx - a Client Component
'use client';
import { useState } from 'react';
export default function AddToCart({ productId }) {
const [added, setAdded] = useState(false);
return <button onClick={() => { cart.add(productId); setAdded(true); }}>{added ? 'Added' : 'Add to cart'}</button>;
}
RSC is not the same as SSR
Server-side rendering turns all components into HTML for the first load, then ships their JavaScript to hydrate. Server Components never ship their JavaScript at all. Frameworks use both together: Server Components for data and layout, SSR for a fast first paint of client components.
Rules for the boundary
'use client'marks a boundary; everything imported into that file becomes client code too.- Server Components can render Client Components and pass them serialisable props (no functions, except Server Functions).
- Pass Server Components into Client Components as
childrento keep them on the server. - Push
'use client'as far down the tree as possible, onto small interactive leaves.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.