React Server Components (RSC) is a new React architecture that allows components to run on the server:
// Server Component
async function ServerComponent() {
const data = await fetch('api/data');
return <div>{data.title}</div>;
}
// Client Component
'use client';
function ClientComponent() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}React Server Components is a revolutionary architecture that changes how we build React applications! They allow components to run on the server, providing numerous benefits. 🚀
Run on the server and send ready HTML:
// app/posts/page.js
async function PostsPage() {
// Runs on server
const posts = await db.posts.findMany();
return (
<div>
<h1>Posts</h1>
{posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</article>
))}
</div>
);
}Run in browser with interactivity:
// components/LikeButton.js
'use client';
import { useState } from 'react';
function LikeButton({ postId }) {
const [liked, setLiked] = useState(false);
return (
<button
onClick={() => setLiked(!liked)}
className={liked ? 'liked' : ''}
>
{liked ? '❤️' : '🤍'} Like
</button>
);
}// Server Component (default)
async function BlogPost({ id }) {
const post = await getPost(id);
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
{/* Client component for interactivity */}
<LikeButton postId={id} />
<Comments postId={id} />
</article>
);
}
// Client Component
'use client';
function Comments({ postId }) {
const [comments, setComments] = useState([]);
useEffect(() => {
loadComments(postId).then(setComments);
}, [postId]);
return (
<div>
{comments.map(comment => (
<div key={comment.id}>{comment.text}</div>
))}
</div>
);
}// Server Component - 0 KB JavaScript
function ProductList() {
const products = await db.products.findMany();
return (
<div>
{products.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
}
// Only interactive parts sent to browser
'use client';
function AddToCart({ productId }) {
return (
<button onClick={() => addToCart(productId)}>
Add to Cart
</button>
);
}// Server Component - secret keys stay on server
async function UserProfile({ userId }) {
const user = await db.users.findUnique({
where: { id: userId },
select: { name: true, email: true } // Don't send password
});
return <div>Hello, {user.name}!</div>;
}// Server Component - ready HTML for search engines
async function ArticlePage({ slug }) {
const article = await getArticle(slug);
return (
<>
<Head>
<title>{article.title}</title>
<meta name="description" content={article.excerpt} />
</Head>
<article>
<h1>{article.title}</h1>
<div dangerouslySetInnerHTML={{ __html: article.content }} />
</article>
</>
);
}// app/dashboard/page.js
import { Suspense } from 'react';
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Suspense fallback={<div>Loading stats...</div>}>
<Stats />
</Suspense>
<Suspense fallback={<div>Loading charts...</div>}>
<Charts />
</Suspense>
</div>
);
}
// Slow server component
async function Stats() {
const stats = await getStats(); // Slow query
return <div>Stats: {stats.total}</div>;
}// Server component passes data to client component
async function PostPage({ params }) {
const post = await getPost(params.id);
const user = await getCurrentUser();
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
{/* Pass data to client component */}
<InteractiveSection
postId={post.id}
userId={user.id}
initialLikes={post.likes}
/>
</div>
);
}
'use client';
function InteractiveSection({ postId, userId, initialLikes }) {
const [likes, setLikes] = useState(initialLikes);
return (
<div>
<button onClick={() => setLikes(likes + 1)}>
👍 {likes}
</button>
</div>
);
}// ❌ Use state hooks
function ServerComponent() {
const [state, setState] = useState(0); // Error!
return <div>{state}</div>;
}
// ❌ Use effects
function ServerComponent() {
useEffect(() => {}, []); // Error!
return <div>Content</div>;
}
// ❌ Use browser APIs
function ServerComponent() {
const width = window.innerWidth; // Error!
return <div>Width: {width}</div>;
}// ❌ Import server modules
'use client';
import { db } from './database'; // Error!
function ClientComponent() {
return <div>Client</div>;
}// ✅ Correct architecture
async function ProductPage({ id }) {
const product = await getProduct(id); // Server
return (
<div>
<ProductInfo product={product} /> {/* Server */}
<AddToCartButton productId={id} /> {/* Client */}
</div>
);
}❌ Wrong:
// Mixing server and client code
function Component() {
const [state, setState] = useState(0);
const data = await fetch('/api'); // Error!
return <div>{data}</div>;
}✅ Correct:
// Separation of concerns
async function ServerComponent() {
const data = await fetch('/api');
return <ClientComponent initialData={data} />;
}
'use client';
function ClientComponent({ initialData }) {
const [state, setState] = useState(0);
return <div>{initialData.title}</div>;
}React Server Components is the future of React development:
Use RSC to build fast and efficient applications! 🚀