Understanding React Server Components
Understanding React Server Components
React Server Components (RSC) represent a fundamental shift in how we think about React applications. They allow components to run exclusively on the server, sending only the rendered output to the client.
Server vs Client Components
The key distinction is simple:
| Feature | Server Component | Client Component |
|---|---|---|
| Runs on | Server only | Server + Client |
| Can use hooks | No | Yes |
| Can access DB | Yes | No |
| Bundle size impact | Zero | Adds to bundle |
| Interactivity | None | Full |
When to Use Each
Use Server Components when:
- Fetching data from a database or API
- Rendering static or mostly-static content
- Using heavy dependencies (markdown parsers, syntax highlighters)
Use Client Components when:
- You need interactivity (click handlers, form inputs)
- You need browser APIs (localStorage, geolocation)
- You need React hooks (useState, useEffect)
A Practical Example
tsx
// This is a Server Component (default in Next.js App Router)
import { prisma } from '@/lib/prisma';
export default async function PostList() {
const posts = await prisma.post.findMany();
return (
<div>
{posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.excerpt}</p>
<LikeButton postId={post.id} />
</article>
))}
</div>
);
}tsx
// This must be a Client Component
"use client";
import { useState } from 'react';
export function LikeButton({ postId }: { postId: string }) {
const [liked, setLiked] = useState(false);
return (
<button onClick={() => setLiked(!liked)}>
{liked ? '❤️' : '🤍'} Like
</button>
);
}The Mental Model
Think of it as a tree where Server Components form the trunk and branches, while Client Components are the leaves where interactivity happens. Data flows down from server to client, never the other way.
Explore by topic