5 min read
ā¢Question 15 of 47mediumWhat are Server Components in Next.js?
Understanding React Server Components.
What You'll Learn
- Server Components concept
- Benefits and trade-offs
- Data fetching patterns
Server Components (Default)
code.txtTSX
// app/page.tsx - Server Component by default
export default async function Page() {
const data = await fetch('https://api.example.com/posts');
const posts = await data.json();
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}Benefits
| Feature | Server | Client |
|---|---|---|
| Data fetching | Direct DB/API | Via API routes |
| Bundle size | Zero JS sent | Adds to bundle |
| SEO | Fully rendered | Requires hydration |
| Secrets | Safe to use | Never use |
| Interactivity | None | Full |
Direct Database Access
code.txtTSX
import { db } from '@/lib/db';
export default async function Users() {
const users = await db.user.findMany();
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}Composition
code.txtTSX
// Server Component with Client child
import { LikeButton } from './LikeButton';
export default async function Post({ id }) {
const post = await getPost(id);
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
<LikeButton postId={id} /> {/* Client Component */}
</article>
);
}