Understanding Server Components in Next.js

Next.js 13 introduced the App Router, and with it, a paradigm shift in how we build React applications: React Server Components (RSCs).
What are Server Components?
Server Components are a new type of component that runs exclusively on the server. They are never downloaded to the client, and their code is not included in the client-side JavaScript bundle.
This has several key advantages:
- Zero Bundle Size: Because they don't ship any JavaScript to the client, they don't contribute to your app's bundle size. This leads to faster initial page loads.
- Direct Backend Access: Server Components can directly access server-side resources like databases, filesystems, or internal APIs without needing to create a separate API endpoint. This simplifies data fetching logic.
- Security: Sensitive data and logic, like API keys or database credentials, can be kept safely on the server and never exposed to the browser.
Server vs. Client Components
In the Next.js App Router, all components are Server Components by default. To create a component that runs on the client (i.e., a traditional React component with state and effects), you need to opt-in with the 'use client'
directive at the top of the file.
'use client';
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
Any component that uses hooks like useState
or useEffect
must be a Client Component.
The Best of Both Worlds
The power of this model lies in the ability to seamlessly interleave Server and Client Components. You can fetch data in a Server Component and pass it as props to an interactive Client Component, getting the best of both worlds: efficient data loading on the server and rich interactivity on the client.