Understanding React Server Components in Next.js
React Server Components (RSC) have changed the way we think about rendering and data fetching in Next.js. In this post, we'll explore the basics of Server Components and look at a quick example.
What are Server Components?
Server Components allow you to render components on the server before sending them to the client. This reduces the JavaScript bundle size and allows for direct access to backend resources like databases or filesystems without needing an API layer.
Example: Fetching Data
Here is a quick example of a Server Component that fetches data directly from a hypothetical database:
import { db } from "@/lib/db";
export default async function UserProfile({ userId }: { userId: string }) {
// Fetch data directly from the database on the server
const user = await db.user.findUnique({
where: { id: userId }
});
if (!user) {
return <div>User not found</div>;
}
return (
<div className="p-4 border rounded-lg shadow-sm">
<h2 className="text-2xl font-bold">{user.name}</h2>
<p className="text-gray-600">{user.email}</p>
</div>
);
}
Notice that this component is async. We can use standard await syntax to fetch data, making the code much simpler than using useEffect on the client.
Benefits
- Zero Client-Side JavaScript: Server components don't add to your bundle size.
- Direct Backend Access: No need to write separate API routes for simple data fetching.
- Automatic Code Splitting: Client components imported inside server components are automatically code-split.
Next.js makes it incredibly easy to start using RSCs with the new App Router. Give it a try!