ReactNext.jsServer Components
React Server Components: A Deep Dive
·12 min read
React Server Components: A Deep Dive
React Server Components (RSC) represent a paradigm shift in how we build React applications. Let's explore what they are and how to use them effectively.
What Are Server Components?
Server Components are React components that render exclusively on the server. They:
- Have zero bundle size impact
- Can directly access backend resources
- Never re-render on the client
// This is a Server Component by default in Next.js App Router
async function UserProfile({ userId }: { userId: string }) {
// Direct database access - no API needed!
const user = await db.user.findUnique({
where: { id: userId }
});
return (
<div>
<h1>{user.name}</h1>
<p>{user.bio}</p>
</div>
);
}When to Use Client Components
Add 'use client' when you need:
- Event handlers (onClick, onChange, etc.)
- State (useState, useReducer)
- Effects (useEffect)
- Browser-only APIs
'use client';
import { useState } from 'react';
function LikeButton({ initialCount }: { initialCount: number }) {
const [count, setCount] = useState(initialCount);
return (
<button onClick={() => setCount(c => c + 1)}>
Likes: {count}
</button>
);
}Composition Patterns
The key is composing Server and Client Components effectively:
// Server Component
async function PostPage({ id }: { id: string }) {
const post = await getPost(id);
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
{/* Client Component for interactivity */}
<LikeButton initialCount={post.likes} />
{/* Server Component for comments */}
<Comments postId={id} />
</article>
);
}Data Fetching Patterns
// Parallel data fetching
async function Dashboard() {
// These run in parallel!
const [user, posts, analytics] = await Promise.all([
getUser(),
getPosts(),
getAnalytics()
]);
return (
<div>
<UserCard user={user} />
<PostList posts={posts} />
<AnalyticsChart data={analytics} />
</div>
);
}Server Components have fundamentally changed how I think about React applications. They enable simpler, faster, and more secure apps.