React — Server Components
What are Server Components?
Server Components run on the server and send rendered HTML to the client. They can't use state or hooks.
Server Component Example
// This runs on the server
async function UserProfile({ userId }) {
const user = await fetchUser(userId);
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
Client Components
// This runs on the client
'use client';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + 1)}>
Increment
</button>
</div>
);
}
Mixing Server and Client Components
// Server component
async function Page() {
const data = await fetchData();
return (
<div>
<h1>Page Title</h1>
<ClientComponent data={data} />
</div>
);
}
// Client component
'use client';
function ClientComponent({ data }) {
const [isExpanded, setIsExpanded] = useState(false);
return (
<div>
<button onClick={() => setIsExpanded(!isExpanded)}>
Toggle
</button>
{isExpanded && <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
}
Server Components Examples
// Data fetching
async function ProductList() {
const products = await fetch('https://api.example.com/products')
.then(res => res.json());
return (
<div className="product-grid">
{products.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
}
// Static content
async function BlogPost({ slug }) {
const post = await getPost(slug);
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
</article>
);
}
Mini Practice
Write React code that:
- Creates a server component
- Creates a client component
- Mixes server and client components
- Fetches data in a server component
Up Next
Next: Learn about State Management.
Related Topics
Frequently Asked Questions about Server Components
What is Server Components in React?
Server Components is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Server Components?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Server Components.
Why is Server Components important in React?
Server Components is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.