Next.jsEasy
What is the difference between Server and Client Components?
Server Components run only on the server and send no JavaScript for themselves; they are for data fetching and static UI. Client Components (marked with "use client") are pre-rendered on the server and then hydrated in the browser; they are for state, effects, event handlers and browser APIs.
Comparison
| Server Component | Client Component | |
|---|---|---|
Default in app/ | Yes | No, needs "use client" |
| Runs in browser | Never | Yes (and SSR'd on the server) |
async component | Yes | No |
| State, effects, event handlers | No | Yes |
| Browser APIs | No | Yes (in effects or handlers) |
| Database and secrets | Yes | No |
| Adds to client bundle | No | Yes |
Choosing
- Server: fetching data, accessing backend resources, keeping secrets, large dependencies, static content.
- Client: interactivity (
onClick,onChange),useState,useEffect, context consumers, browser APIs likelocalStorage, and hooks-based libraries.
Composition rules
- Server Components can import and render Client Components.
- Client Components cannot import Server Components, but can receive them as
childrenor other props. - Props from server to client must be serializable.
"use client"marks a boundary: everything that module imports becomes client code too.
Best practice
Keep client boundaries small and at the leaves: make the search input a Client Component, not the whole page. Use the server-only and client-only packages to get build errors when code is imported on the wrong side.
Code example
tsx
1// app/products/page.tsx - Server Component (default)2import { db } from "@/lib/db";3import { AddToCart } from "./add-to-cart";45export default async function Products() {6 const products = await db.product.findMany(); // server-only access7 return (8 <ul>9 {products.map((p) => (10 <li key={p.id}>11 {p.name} - ${p.price}12 <AddToCart id={p.id} />13 </li>14 ))}15 </ul>16 );17}1819// app/products/add-to-cart.tsx - Client Component20// "use client";21// import { useState } from "react";22// export function AddToCart({ id }: { id: string }) {23// const [added, setAdded] = useState(false);24// return <button onClick={() => setAdded(true)}>{added ? "Added" : "Add to cart"}</button>;25// }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.