What Are 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, reducing the JavaScript bundle sent to the client and enabling direct access to backend resources.
Key Benefits
Server Components offer several advantages:
- Smaller Bundle Size: Server Components never ship to the client, reducing JavaScript payload
- Direct Backend Access: Query databases and access file systems directly in components
- Improved Performance: Less JavaScript means faster page loads and better Core Web Vitals
- Automatic Code Splitting: Only client components are bundled for the browser
Server vs Client Components
// This is a Server Component by default
async function BlogList() {
const posts = await db.posts.findMany()
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)// Add 'use client' for client interactivity 'use client' function LikeButton({ postId }) { const [likes, setLikes] = useState(0) return <button onClick={() => setLikes(l => l + 1)}>{likes}</button> } ```
Best Practices
- . Start with Server Components - Only add 'use client' when you need interactivity
- . Keep client boundaries small - Push 'use client' as far down the tree as possible
- . Pass serializable props - Data passed from server to client must be serializable
- . Use Suspense for loading states - Wrap async components in Suspense boundaries
When to Use Client Components
Use client components when you need:
- Event listeners (onClick, onChange, etc.)
- State and lifecycle effects (useState, useEffect)
- Browser-only APIs
- Custom hooks that depend on state or effects