Server vs Client Components
In the App Router, components run on the server by default — and you opt in to the browser only when you need to.
What you will learn
- Explain a Server Component
- Know when you need a Client Component
- Use the use client directive correctly
A big shift from plain React
In a normal React app, every component runs in the browser. In the Next.js App Router, components are Server Components by default — they run on the server, never ship their code to the browser, and can safely talk to a database or read secret keys.
When you must use a Client Component
Server Components cannot use the interactive React features, because those need a browser. The moment you need any of these, you make a Client Component:
- State —
useState. - Effects —
useEffect. - Event handlers —
onClick,onChange, etc. - Browser-only things like
windoworlocalStorage.
Opt in with one line
To make a Client Component, put the string use client as the very first line of the file. Everything else is the React you already know.
'use client';
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}Note: Output: Clicked 0 times <- and the number rises each click Because this uses useState and onClick, it must run in the browser. The "use client" line tells Next.js to ship it to the browser and make it interactive.
| Server Component (default) | Client Component (use client) | |
|---|---|---|
| Runs | On the server | In the browser |
| useState / useEffect | No | Yes |
| onClick handlers | No | Yes |
| Talk to a database directly | Yes (safe) | No |
| Ships JS to browser | No (smaller, faster) | Yes |
Watch out: Do not add use client to everything out of habit. Server Components ship no JavaScript to the browser, which makes pages faster. Keep components on the server unless they truly need interactivity.
Tip: A great pattern: keep the page a Server Component (it fetches data), and put just the small interactive bits — a button, a form, a like-counter — in their own Client Components.
Q. When do you need to mark a component with use client?
✍️ Practice
- Write a
CounterClient Component and add it to a page. - Decide for each: a static About section, a search box with typing, a footer — server or client?
🏠 Homework
- Build a page that is a Server Component but includes one small Client Component (a toggle button) inside it.