Lesson 177 of 296
Server Components vs Client Components
What you will learn
- What a Server Component is
- What a Client Component is and the "use client" directive
- What each can and cannot do
- Where the boundary goes, and why to keep it low
- Passing data and Server Components into Client Components
- server-only and serialisation rules
On this page
Two kinds of components
In the App Router, every component is a Server Component by default.
A Server Component runs only on the server (at build time or per request). Its code is never sent to the browser. It sends the browser the result: HTML for the first load, plus a compact description of the UI (the "RSC payload").
A Client Component is marked with "use client" at the top of its file. It is rendered to HTML on the server for the first load too, and then its JavaScript is sent to the browser, where it hydrates (React attaches event handlers and state to the existing HTML) and becomes interactive.
So "Client Component" does not mean "only renders in the browser". It means "also runs in the browser".
What each can do
| Server Component | Client Component | |
|---|---|---|
Fetch data, await | Yes, directly (can be async) | Not directly during render (use a library or receive props) |
| Access database, files, secrets | Yes, safely | Never: the code is public |
| useState, useEffect, useReducer | No | Yes |
| Event handlers (onClick, onChange) | No | Yes |
| Browser APIs (window, localStorage) | No | Yes (in effects and handlers) |
| JavaScript sent to the browser | None | Yes, the component and its imports |
Example
A product page: the data loading is on the server; only the "Add to basket" button needs interactivity.
"use client";
import { useState } from "react";
export function AddToBasketButton({ sku }: { sku: string }) {
const [added, setAdded] = useState(false);
return (
<button type="button" onClick={() => setAdded(true)} disabled={added} data-sku={sku}>
{added ? "Added" : "Add to basket"}
</button>
);
}import { AddToBasketButton } from "./add-to-basket-button";
import { getProduct } from "@/lib/db";
import { notFound } from "next/navigation";
export default async function ProductPage({ params }: { params: Promise<{ sku: string }> }) {
const { sku } = await params;
const product = await getProduct(sku);
if (!product) notFound();
return (
<article>
<h1>{product.name}</h1>
<p>£{(product.pricePence / 100).toFixed(2)}</p>
<AddToBasketButton sku={product.sku} />
</article>
);
}The page queries the database directly. Only the small button's JavaScript reaches the browser.
"use client" marks a boundary
"use client" goes at the top of a file. It marks the point where code crosses from server to client: that component, and every component it imports, becomes part of the client bundle.
Keep the boundary as low (as deep in the tree) as possible. Do not put "use client" on a whole page just because one button needs state. Extract the interactive part into a small Client Component, like the button above. Less JavaScript means faster pages.
Passing Server Components into Client Components
A Client Component cannot import a Server Component (the import would pull it into the client bundle). But it can receive one as children or another prop, because the server renders it first and passes the result:
"use client";
import { useState, type ReactNode } from "react";
export function Collapsible({ title, children }: { title: string; children: ReactNode }) {
const [open, setOpen] = useState(false);
return (
<section>
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
{title}
</button>
{open && children}
</section>
);
}In a Server Component page: <Collapsible title="Reviews"><Reviews /></Collapsible>, where Reviews is an async Server Component that loads reviews from the database. This is composition (Lesson 165) across the server and client boundary.
Props must be serialisable
Props passed from a Server Component to a Client Component travel over the network, so they must be serialisable: strings, numbers, booleans, null, plain objects and arrays, Date, Map, Set, promises, and JSX. You cannot pass ordinary functions (except server actions, Lesson 181), class instances with methods, or symbols.
Also be careful what you pass: everything sent to a Client Component is visible in the browser. Pass only the fields needed (never a whole user record with a password hash).
Keeping server code on the server
Mark modules that must never reach the browser (database access, secret keys) with:
import "server-only";If a Client Component imports such a module by mistake, the build fails instead of leaking secrets. Similarly, environment variables are server-only unless their name starts with NEXT_PUBLIC_ (those are copied into the browser bundle, so never put secrets in them).
Context and libraries
Context providers use state, so they must be Client Components. Common pattern: a providers.tsx file with "use client" that wraps children with your theme or query-client providers, used in the root layout. The pages inside can still be Server Components (they are passed as children).
How to say it in an interview
"In the App Router, components are Server Components by default: they run only on the server, can be async and read the database or secrets directly, and send no JavaScript to the browser. 'use client' marks a boundary where components also run in the browser and hydrate, so they can use state, effects and event handlers. I keep that boundary as low as possible, pass Server Components into Client Components as children, pass only serialisable and minimal props, and protect server modules with server-only and non-public environment variables."
Key words
| Word | Meaning |
|---|---|
| Server Component | Runs only on the server; sends no JavaScript |
| Client Component | Marked "use client"; also runs and hydrates in the browser |
| Hydration | React attaching interactivity to server-rendered HTML |
| RSC payload | The compact description of the server-rendered UI |
| Boundary | The point where server code meets client code |
| Serialisable | Data that can be turned into text and sent over the network |
| server-only | A package that makes the build fail if server code reaches the client |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.