Server Components vs Client Components
MediumReactServer ComponentsNext.js
What's the difference between React Server Components and Client Components, and how do you decide which to use?
TL;DR
Server Components run only on the server (at build time or per request). Their code never ships to the browser, they can be async and read data directly (database, file system, secrets), but they can't use state, effects or browser APIs. Client Components are marked with 'use client'. They're pre-rendered to HTML on the server too, then their JavaScript is sent to the browser and hydrated, so they can be interactive. Default to Server Components and add 'use client' only at the leaves that need interactivity.
Key points
'use client'marks a boundary: that file and everything it imports become client code.- A Server Component can render a Client Component and pass it serializable props (no functions, except Server Actions).
- A Client Component can't import a Server Component, but it can receive one as
children. - RSC vs SSR: SSR turns components into HTML for the first load, then the client hydrates all of them. RSC removes server-only components from the client bundle entirely. They work together.
- Benefits: smaller bundles, no client-side request waterfalls for data, secrets stay on the server.
- Server Actions (
'use server') let client code call a server function, for example to submit a form.
Example
tsx
// app/products/page.tsx: Server Component (the default)
export default async function ProductsPage() {
const products = await db.product.findMany()
return products.map((p) => (
<article key={p.id}>
<h2>{p.name}</h2>
<AddToCartButton id={p.id} />
</article>
))
}
// add-to-cart-button.tsx
;('use client')
export function AddToCartButton({ id }: { id: string }) {
const [pending, setPending] = useState(false)
return (
<button
disabled={pending}
onClick={() => {
setPending(true)
addToCart(id)
}}
>
Add
</button>
)
}Common follow-ups
- Why can't Server Components use hooks? They render once on the server and never re-render in the browser, so there's no state or lifecycle.
- Where should the
'use client'boundary go? As deep as possible: wrap the small interactive piece, not the whole page.
What interviewers look for
Tip
Where each kind runs, what each can and can't do, how RSC differs from SSR, and pushing 'use client' down to the leaves.
- Red flag: "Server Components are the same as SSR", or putting
'use client'at the top of every page.