React Server Components (RSC)
📖 Concept
Server Components represent the biggest shift in React's mental model in years. They allow you to render some components entirely on the server, sending only the final HTML (and a special serializable format) to the browser.
Client vs Server Components:
- Server Components (Default in App Router): Can fetch data directly from a database, use secret keys, and have zero impact on your JavaScript bundle size. They cannot use hooks (
useState,useEffect) or browser APIs. - Client Components (
'use client'): Can use hooks and browser APIs. These are sent to the client as JavaScript and "hydrated".
The Boundary Rule:
You can import a Client Component into a Server Component, but you cannot import a Server Component into a Client Component. Instead, you should pass Server Components as children or props to Client Components.
Why RSC?
- Zero-Bundle-Size: Complex libraries used on the server don't get sent to the user.
- Direct Data Access: No need for a separate API layer just to fetch data for your UI.
- Improved Performance: Faster initial load and less JavaScript to execute.
💻 Code Example
1// 1. A Server Component (page.tsx)2// Can be async!3async function BlogPage() {4 // Fetch data directly from a database or API5 const posts = await db.post.findMany();67 return (8 <div>9 <h1>My Blog</h1>10 {posts.map(post => (11 <article key={post.id}>12 <h2>{post.title}</h2>13 {/* 2. Pass data to a Client Component */}14 <LikeButton postId={post.id} />15 </article>16 ))}17 </div>18 );19}2021// 3. A Client Component (LikeButton.tsx)22'use client'; // Required to use hooks23import { useState } from 'react';2425function LikeButton({ postId }) {26 const [likes, setLikes] = useState(0);2728 return (29 <button onClick={() => setLikes(likes + 1)}>30 {likes} Likes31 </button>32 );33}
🏋️ Practice Exercise
- Set up a Next.js App Router project and identify which components are Server vs Client.
- Try to use
useEffectin a Server Component and observe the error message. - Fetch data in a Server Component and pass it as props to a Client Component.
- Research the 'Serialization' rule: why can't you pass a function or a complex class instance from a Server Component to a Client Component?
⚠️ Common Mistakes
Adding 'use client' to every file (this defeats the purpose of RSC).
Trying to pass non-serializable data (like a function or a Date object) across the server-client boundary.
Forgetting to add 'use server' to functions that are used as Server Actions.
Over-using Client Components for simple things that could be handled on the server.
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for React Server Components (RSC)