Server vs Client Components
Server Components vs Client Components is the most important mental model in the Next.js App Router. Server Components run only on the server. Client Components run in the browser. Every component you write is one or the other, and choosing correctly affects performance, security, and user experience.
This tutorial explains what each type does, the "use client" directive, the client boundary, and how to pass data between them. You will build a page that fetches data on the server and includes a small interactive button on the client. If you are new to the App Router, read Next.js Middleware first, or start with Next.js App Router Basics if routing is still unclear.
What Are Server Components and Client Components?
Server Components are React components that run only on the server and send HTML to the browser. Client Components are React components that run in the browser and support interactivity. In the App Router, Server Components are the default. You add "use client" to opt into a Client Component .
// app/example/page.tsx
// This is a Server Component by default.
export default function ExamplePage() {
return <h1>Rendered on the server</h1>;
}
How it works: The file has no "use client" directive, so Next.js treats it as a Server Component. It runs during the request on the server, produces HTML, and sends that HTML to the browser. No component JavaScript for this file is sent to the client unless it imports a Client Component.
What Is the "use client" Directive?
The "use client" directive marks a file and all its imports as Client Components. It must be the first statement in the file, before any imports. Once a file is a Client Component, it can use state, effects, event handlers, and browser APIs .
// app/components/Counter.tsx
"use client";
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Add one</button>
</div>
);
}
Browser shows:
Count: 0
[Add one] ← clicking increments the count
How it works: The directive tells Next.js to bundle this component for the browser. The useState hook and the onClick handler require a browser environment. Without the directive, Next.js would throw an error because Server Components cannot use state or event handlers. The directive does not make the component client-only in the HTML sense. It still renders on the server for the initial HTML, then hydrates in the browser.
When Should You Use Each Type?
The choice depends on what the component needs to do. Use the table below as a quick reference.
| Need | Server Component | Client Component |
|---|---|---|
| Fetch data from a database | Yes | No |
| Access secrets or API keys | Yes | No |
Use useState or useReducer |
No | Yes |
Use useEffect |
No | Yes |
Add event handlers like onClick |
No | Yes |
Access window or localStorage |
No | Yes |
| Reduce JavaScript sent to browser | Yes | No |
How it works: Server Components keep sensitive logic and large dependencies on the server. Client Components handle anything that needs the browser. Start with Server Components and add Client Components only where interactivity is required. This keeps your bundle small and your data safe.
What Is the Client Boundary and How Does It Spread?
The client boundary is the line between server and client code. When a file has "use client", every component it imports also becomes a Client Component. The boundary spreads downward through the import tree .
// app/components/ClientParent.tsx
"use client";
import Child from "./Child";
export default function ClientParent() {
return <Child />;
}
// app/components/Child.tsx
// No "use client" here, but it becomes a Client Component
// because it is imported by ClientParent.
export default function Child() {
return <p>I am now a Client Component.</p>;
}
How it works: Child.tsx has no directive of its own. But because ClientParent imports it, and ClientParent is a Client Component, Child becomes part of the client bundle. The boundary does not spread upward. A Server Component can import a Client Component, but the reverse is not true for making server code.
How Do You Pass Server Components as Children into Client Components?
A Client Component cannot import a Server Component directly. But it can receive one as a children prop. The Server Component renders on the server, and the resulting HTML is passed into the Client Component .
// app/components/Collapsible.tsx
"use client";
import { useState } from "react";
export default function Collapsible({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const [open, setOpen] = useState<boolean>(false);
return (
<div>
<button onClick={() => setOpen(!open)}>
{open ? "Hide" : "Show"}
</button>
{open && children}
</div>
);
}
// app/page.tsx (Server Component)
import Collapsible from "./components/Collapsible";
export default function HomePage() {
return (
<Collapsible>
<p>This content was rendered on the server.</p>
</Collapsible>
);
}
Browser shows:
[Show] ← clicking reveals the server-rendered paragraph
How it works: The page is a Server Component. It renders the paragraph on the server and passes it as children to Collapsible. The Client Component controls whether to display the children, but the children themselves stay server-rendered. This pattern lets you wrap server content in interactive UI without turning the whole page into a Client Component.
Why Must Props Be Serializable?
Props passed from a Server Component to a Client Component must be serializable. That means they must be values that can cross the network boundary: strings, numbers, booleans, plain objects, arrays, and some special values like Date and Map. Functions, class instances, and Symbol values cannot be passed .
// app/page.tsx (Server Component)
import LikeButton from "./components/LikeButton";
export default function HomePage() {
const postId = "post-123";
return <LikeButton postId={postId} />;
}
// app/components/LikeButton.tsx
"use client";
export default function LikeButton({ postId }: { postId: string }) {
return <button>Like {postId}</button>;
}
How it works: The string postId can be sent from server to client because it is serializable. If you tried to pass a function like onLike={() => {}} from a Server Component, Next.js would throw an error. Define functions inside the Client Component instead, or use Server Actions for mutations.
What Error Do You Get When Using useState in a Server Component?
Using a client-only hook in a Server Component produces a clear error. Next.js tells you to add the directive or move the hook into a Client Component .
// app/broken/page.tsx
import { useState } from "react";
export default function BrokenPage() {
const [value] = useState<string>("hello");
return <p>{value}</p>;
}
// Error: You're importing a component that needs `useState`.
// This React hook only works in a client component.
// To fix, mark the file (or its parent) with the "use client" directive.
How it works: Server Components do not have a client-side runtime, so hooks like useState and useEffect are unavailable. The fix is to either add "use client" at the top of the file or move the hook into a separate Client Component and import it. Adding the directive to the whole page works, but it turns the entire page into a Client Component. Prefer moving only the interactive part into its own small file.
Common Mistakes and Best Practices
- Adding
"use client"to every file. This turns your entire app into client code and loses the benefits of server rendering. Start without the directive and add it only where you need state, effects, event handlers, or browser APIs. - Importing a Server Component inside a Client Component. A Client Component cannot import a Server Component directly. Pass the Server Component as
childrenfrom a parent Server Component instead. The boundary only allows server-to-client imports, not the reverse. - Trying to pass functions as props from server to client. Functions are not serializable. Passing them causes a runtime error. Define event handlers inside the Client Component, or use Server Actions to handle mutations on the server.
- Fetching data in Client Components unnecessarily. Server Components can fetch data directly and keep API keys private. Use Client Components for interactivity, not for data loading that does not need to run in the browser.
- Making large Client Components. Every Client Component adds JavaScript to the bundle. Keep Client Components small and move them to the leaves of the component tree so most of your app stays on the server.
Real-World Example: A Server-Rendered List with a Client Like Button
This example fetches a post on the server, renders it, and includes a small interactive like button on the client.
// app/components/LikeButton.tsx
"use client";
import { useState } from "react";
export default function LikeButton({ initialLikes }: { initialLikes: number }) {
const [likes, setLikes] = useState<number>(initialLikes);
return (
<button onClick={() => setLikes(likes + 1)}>
Likes: {likes}
</button>
);
}
// app/page.tsx (Server Component)
import LikeButton from "./components/LikeButton";
type Post = {
id: string;
title: string;
likes: number;
};
async function getPosts(): Promise<Post[]> {
// Simulated data fetch. Replace with a real API or database call.
return [
{ id: "1", title: "Learning Server Components", likes: 12 },
{ id: "2", title: "Understanding Client Boundaries", likes: 8 },
];
}
export default async function HomePage() {
const posts = await getPosts();
return (
<main>
<h1>Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>
<h2>{post.title}</h2>
<LikeButton initialLikes={post.likes} />
</li>
))}
</ul>
</main>
);
}
Browser shows:
Posts
Learning Server Components
[Likes: 12] ← clicking increments to 13
Understanding Client Boundaries
[Likes: 8] ← clicking increments to 9
Line-by-line explanation: LikeButton.tsx starts with "use client" because it uses useState and onClick. It accepts a number prop initialLikes, which is serializable. The page file has no directive, so it is a Server Component. The getPosts function runs on the server and returns an array of posts. The page component is async and awaits the data. It maps over the posts and renders a LikeButton for each one, passing the server-fetched like count as a prop. Only the button's JavaScript is sent to the browser. The rest of the page, including the post list and headings, stays on the server. The example is complete and compiles with TypeScript strict mode.
Summary
- Server Components run only on the server and are the default in the App Router. Client Components run in the browser and need the
"use client"directive. - Use Server Components for data fetching, secrets, and large dependencies. Use Client Components for state, effects, event handlers, and browser APIs.
- The client boundary spreads downward through imports. A Server Component can import a Client Component, but a Client Component cannot import a Server Component directly.
- Pass Server Components as
childreninto Client Components to combine interactivity with server-rendered content. - Props from server to client must be serializable. Functions and class instances cannot be passed across the boundary.
- Keep Client Components small and at the leaves of the tree to minimise the JavaScript bundle.
Now that you understand the component model, continue to SSR, SSG & ISR Explained to learn how Next.js renders pages at different times.
Frequently Asked Questions
Can a Client Component import a Server Component?
No. A Client Component cannot import a Server Component directly because the import would pull server code into the client bundle. Instead, pass the Server Component as a children prop from a parent Server Component. The Server Component renders on the server, and the resulting content is passed into the Client Component.
Why does useState fail in a Server Component?
Server Components have no client-side runtime. They run on the server, where React does not mount components or track state over time. Hooks like useState and useEffect need a browser. Next.js throws an error that tells you to add "use client" or move the hook into a Client Component.
Does "use client" mean the component never runs on the server?
No. Client Components still render on the server for the initial HTML. The directive tells Next.js to bundle the component for the browser so it can hydrate and handle interactivity. The component's server render produces the first HTML, then the browser takes over after hydration.
Can I pass a function as a prop to a Client Component?
No, not from a Server Component. Functions are not serializable, so they cannot cross the network boundary. Define event handlers inside the Client Component itself. For mutations, use Server Actions, which are designed to be called from Client Components and executed on the server.
How do I share data between a Server Component and a Client Component?
Pass the data as props from the Server Component to the Client Component. The data must be serializable, like strings, numbers, plain objects, or arrays. Fetch the data in the Server Component, then pass only what the Client Component needs. This keeps sensitive data and large dependencies on the server.
Practice Exercises
Easy: Mark a Component as Client
Create a component that uses useState to toggle between "On" and "Off". Add the correct directive.
Show solution
// app/components/Toggle.tsx
"use client";
import { useState } from "react";
export default function Toggle() {
const [on, setOn] = useState<boolean>(false);
return (
<button onClick={() => setOn(!on)}>
{on ? "On" : "Off"}
</button>
);
}
The "use client" directive is required because the component uses state and an event handler.
Easy: Fix the useState Error
This Server Component uses useState and fails. Fix it by moving the hook into a Client Component.
// app/broken/page.tsx
import { useState } from "react";
export default function BrokenPage() {
const [count] = useState<number>(0);
return <p>{count}</p>;
}
Show solution
// app/components/CounterDisplay.tsx
"use client";
import { useState } from "react";
export default function CounterDisplay() {
const [count] = useState<number>(0);
return <p>{count}</p>;
}
// app/fixed/page.tsx
import CounterDisplay from "../components/CounterDisplay";
export default function FixedPage() {
return <CounterDisplay />;
}
Moving the hook into a Client Component fixes the error without making the entire page a Client Component.
Medium: Pass a Server Component as Children
Create a Client Component called Accordion that toggles visibility. Pass a server-rendered paragraph as its children from a Server Component page.
Show solution
// app/components/Accordion.tsx
"use client";
import { useState } from "react";
export default function Accordion({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const [open, setOpen] = useState<boolean>(false);
return (
<div>
<button onClick={() => setOpen(!open)}>
{open ? "Close" : "Open"}
</button>
{open && children}
</div>
);
}
// app/page.tsx
import Accordion from "./components/Accordion";
export default function HomePage() {
return (
<Accordion>
<p>This paragraph was rendered on the server.</p>
</Accordion>
);
}
The children are server-rendered and passed into the Client Component through the children prop.
Challenge: Build a Server-Fetched List with a Client Like Button
Create a Server Component page that fetches a typed array of items. Render each item with a Client Component LikeButton that takes a numeric prop and increments on click.
Show solution
// app/components/LikeButton.tsx
"use client";
import { useState } from "react";
export default function LikeButton({ initialLikes }: { initialLikes: number }) {
const [likes, setLikes] = useState<number>(initialLikes);
return (
<button onClick={() => setLikes(likes + 1)}>
Likes: {likes}
</button>
);
}
// app/page.tsx
import LikeButton from "./components/LikeButton";
type Item = {
id: string;
name: string;
likes: number;
};
async function getItems(): Promise<Item[]> {
return [
{ id: "1", name: "First Item", likes: 5 },
{ id: "2", name: "Second Item", likes: 10 },
];
}
export default async function HomePage() {
const items = await getItems();
return (
<ul>
{items.map((item) => (
<li key={item.id}>
<p>{item.name}</p>
<LikeButton initialLikes={item.likes} />
</li>
))}
</ul>
);
}
The page stays a Server Component and fetches data. Only the button is a Client Component, keeping the bundle small.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
