ReactArchitecture

Understanding React Server Components from the Ground Up

2024-03-1012 min
分享

The Problem RSC Solves

Traditional React apps ship all component code to the client, even components that only render static content. Server Components flip this — they run on the server, send rendered output to the client, and never ship their JavaScript.

How It Works

React Server Components introduce a new rendering model with two component types:

  • Server Components (default in Next.js App Router) — Run on the server, can access databases directly, zero client JS
  • Client Components — Marked with 'use client', run in the browser, handle interactivity
// This is a Server Component — no JS shipped to client
async function PostList() {
  const posts = await db.posts.findMany();
  return (
    <ul>
      {posts.map(post => <PostItem key={post.id} post={post} />)}
    </ul>
  );
}

The Mental Model

Think of it as a tree where Server Components form the trunk and branches, and Client Components are the leaves where interactivity happens. Data flows down from server to client, never the other way.

Common Pitfalls

  1. Importing client code in server components — This silently breaks. Keep the boundary clean.
  2. Overusing 'use client' — Don't mark entire pages as client components. Push the boundary as far down as possible.
  3. Serialization limits — Props passed from server to client must be serializable. No functions, no classes.

When to Use What

Use Server Components for data fetching, static layouts, and anything that doesn't need useState, useEffect, or browser APIs. Use Client Components for forms, modals, animations, and interactive widgets.

评论 (0)

还没有评论,来说点什么吧。