Server vs Client Components
Server Components = default, Client Components = 'use client'
Server Components
Render on server, no JavaScript sent
Server Components:
- Run on the server
- No JavaScript bundle sent to client
- Can access backend directly
- Better performance
"Server Components render on the server, reducing JavaScript sent to the client and enabling direct backend access."
Client Components
'use client' directive
'use client';
export default function InteractiveComponent() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
- Use for interactivity
- Hooks (
useState,useEffect) - Event handlers
- Browser APIs
"Client Components use the 'use client' directive and enable interactivity with hooks and event handlers."
When to Use What
Server = default, Client = interactivity
| Use Server Components For | Use Client Components For |
|---|---|
| Data fetching | Interactivity (onClick, etc.) |
| Access backend resources | Hooks (useState, useEffect) |
| Keep sensitive info on server | Browser APIs |
| Reduce client JS | Third-party libraries |
Composition Pattern
Server wraps Client
// Server Component
export default function Page() {
return (
<div>
<ServerData />
<ClientInteractive />
</div>
);
}
"Server Components can import and render Client Components, but not vice versa."
Data Fetching
Server = async, Client = useEffect
Server Components:
export default async function ServerPage() {
const data = await fetch('...');
return <div>{data}</div>;
}
Client Components:
"use client";
export default function ClientPage() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("...").then(setData);
}, []);
}
Benefits of Server Components
- Smaller bundles: Less JavaScript
- Faster initial load: Pre-rendered
- Better SEO: Content in HTML
- Secure: Secrets stay on server
"Server Components reduce bundle size, improve performance, and keep sensitive data secure."
"Next.js App Router uses Server Components by default, which render on the server and don't send JavaScript to the client. Client Components use the 'use client' directive for interactivity, hooks, and browser APIs. Server Components can fetch data directly and compose Client Components, but Client Components cannot import Server Components."
🧠 Ultra-Short Cheat Sheet
Server Components = default
Client Components = 'use client'
Server = data fetching, secure
Client = interactivity, hooks
Server can import Client
Client cannot import Server