使用 React Server Components 构建现代应用
深入探讨 React Server Components 的工作原理、使用场景和最佳实践。
React Server Components (RSC) 代表了 React 生态系统的重大演进。本文将深入探讨 RSC 的核心概念和实践应用。
什么是 Server Components?
Server Components 是一种在服务器端渲染的 React 组件,它们具有以下特点:
- 零客户端 JavaScript - 组件代码不会发送到客户端
- 直接访问服务端资源 - 可以直接查询数据库
- 自动代码分割 - 只发送必要的客户端代码
基本示例
// app/posts/page.tsx - 这是一个 Server Componentasync function PostsPage() { // 直接在组件中获取数据 const posts = await db.post.findMany({ orderBy: { createdAt: 'desc' }, take: 10, });
return ( <main> <h1>最新文章</h1> <ul> {posts.map((post) => ( <li key={post.id}> <a href={`/posts/${post.slug}`}> {post.title} </a> </li> ))} </ul> </main> );}
export default PostsPage;Client Components
当你需要交互性时,使用 "use client" 指令:
"use client";
import { useState } from 'react';
export function Counter() { const [count, setCount] = useState(0);
return ( <button onClick={() => setCount(c => c + 1)}> 点击次数: {count} </button> );}组合模式
Server Components 和 Client Components 可以优雅地组合:
// Server Componentimport { Counter } from './Counter'; // Client Component
async function Dashboard() { const stats = await fetchStats();
return ( <div> <h1>仪表板</h1> <p>总访问量: {stats.visits}</p> {/* 嵌入 Client Component */} <Counter /> </div> );}性能考量
使用 RSC 时的性能公式可以表示为:
其中:
- 是服务器渲染时间
- 是网络传输时间
- 是客户端 hydration 时间
RSC 通过减少 来优化整体性能。
最佳实践
- 默认使用 Server Components - 只在需要时使用 Client Components
- 将交互性下移 - 让 Client Components 尽可能小
- 合理使用 Suspense - 提供良好的加载体验
RSC 正在重塑我们构建 React 应用的方式,值得深入学习和实践。