React Server Components (RSC)

0/2 in this phase0/36 across the roadmap

📖 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?

  1. Zero-Bundle-Size: Complex libraries used on the server don't get sent to the user.
  2. Direct Data Access: No need for a separate API layer just to fetch data for your UI.
  3. Improved Performance: Faster initial load and less JavaScript to execute.

💻 Code Example

codeTap to expand ⛶
1// 1. A Server Component (page.tsx)
2// Can be async!
3async function BlogPage() {
4 // Fetch data directly from a database or API
5 const posts = await db.post.findMany();
6
7 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}
20
21// 3. A Client Component (LikeButton.tsx)
22'use client'; // Required to use hooks
23import { useState } from 'react';
24
25function LikeButton({ postId }) {
26 const [likes, setLikes] = useState(0);
27
28 return (
29 <button onClick={() => setLikes(likes + 1)}>
30 {likes} Likes
31 </button>
32 );
33}

🏋️ Practice Exercise

  1. Set up a Next.js App Router project and identify which components are Server vs Client.
  2. Try to use useEffect in a Server Component and observe the error message.
  3. Fetch data in a Server Component and pass it as props to a Client Component.
  4. 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)