React Server Components: A Deep Dive
Understanding React Server Components, their benefits, limitations, and when to use them in your Next.js applications.
React Server Components (RSC) represent a paradigm shift in how we build React applications. Let’s understand what they are and when to use them.
What Are Server Components?
Server Components are React components that render exclusively on the server. They never ship JavaScript to the client.
// This component runs only on the server
async function BlogPosts() {
const posts = await db.posts.findMany();
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
Benefits
1. Zero Client-Side JavaScript
Server Components don’t add to your JavaScript bundle. The component code stays on the server.
2. Direct Database Access
async function UserProfile({ userId }) {
// Direct database access - no API needed
const user = await prisma.user.findUnique({
where: { id: userId }
});
return <Profile user={user} />;
}
3. Automatic Code Splitting
Only the Client Components you use get sent to the browser.
Server vs Client Components
| Feature | Server | Client |
|---|---|---|
| Fetch data | ✅ | ⚠️ useEffect |
| Use hooks | ❌ | ✅ |
| Event handlers | ❌ | ✅ |
| Browser APIs | ❌ | ✅ |
When to Use Each
Use Server Components for:
- Data fetching
- Accessing backend resources
- Keeping sensitive data on server
- Large dependencies
Use Client Components for:
- Interactivity (onClick, onChange)
- State (useState, useReducer)
- Effects (useEffect)
- Browser-only APIs
The ‘use client’ Directive
Mark Client Components explicitly:
'use client';
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
Conclusion
Server Components offer significant performance benefits by keeping code on the server. Use them by default and reach for Client Components only when you need interactivity.