SkillPilotAI

Server Components vs Client Components

In the Next.js App Router every component is a Server Component unless you opt out with "use client". Knowing where code runs explains the strange useState errors, the 'use client' boundary, serialisable props and hydration errors.

61.1 The problem: useState in a page

  • A like button with useState and onClick works in plain React, but in app/page.tsx Next.js throws an error at npm run dev.
  • Reason: files in the app folder are React Server Components by default, and useState is only available in Client Components.
React (TSX)
// app/page.tsximport { useState } from "react"; export default function Page() {  const [likes, setLikes] = useState(0);  const like = () => setLikes(likes + 1);  return (    <button onClick={like}>      Likes: {likes}    </button>  );}
Output
$ npm run dev⨯ ./app/page.tsx:1:10Error: You're importing a module thatdepends on `useState` into a ReactServer Component module. This API isonly available in Client Components. To fix,mark the file (or its parent) withthe `"use client"` directive.

61.2 Why is it used?

  • A Server Component runs only on the server; its JavaScript never reaches the browser, so the bundle is smaller.
  • It can be async and read the database or secret keys directly; that code never ships to the client.
  • There are no clicks or state changes on the server, so useState, useEffect, onClick and browser APIs cannot work there.
  • For interactivity you need a Client Component, created by writing "use client" at the top of the file.
Why the useState error appears
  1. 1.File in app/ has no directive -> Server Component by default

  2. 2.It runs only on the server, no JS sent to the browser

  3. 3.useState / onClick need the browser

  4. 4.Next.js stops with: only available in Client Components

  5. 5.Fix: move the interactive part into a "use client" file

61.3 Fix: a separate Client Component

  • Move the button into its own file with "use client" on the first line; the rest of the code is unchanged.
  • The page keeps no directive, so it stays a Server Component and can be an async function that awaits data.
  • Heading and student count arrive ready from the server; only LikeButton's JS goes to the browser.
React (TSX)
// app/LikeButton.tsx"use client"; import { useState } from "react"; export function LikeButton() {  const [likes, setLikes] = useState(0);  const like = () => setLikes(likes + 1);  return (    <button onClick={like}>      Likes: {likes}    </button>  );}
React (TSX)
// app/page.tsx (no directive = Server Component)import { LikeButton } from "./LikeButton";import { getCourse } from "./data"; export default async function Page() {  const course = await getCourse();  return (    <main>      <h1>{course.title}</h1>      <p>{course.students} students</p>      <LikeButton />    </main>  );}
Output
# Next.js1200 students[button] Likes: 0 (after one click)# Next.js1200 students[button] Likes: 1

61.4 The 'use client' boundary

  • "use client" marks a boundary: that file and every component it imports become part of the client bundle.
  • Keep the boundary as low in the tree as possible: on the small button or form, not on the whole page.
  • Layout, heading and data stay on the server, so the browser downloads less JavaScript.
Component tree with the boundary low
  1. 1.page.tsx: Server Component (async, reads data)

  2. 2.<h1> and data: rendered on the server, zero JS

  3. 3.<LikeButton />: "use client" boundary

  4. 4.Only LikeButton (and its imports) go into the client bundle

Push 'use client' down to the leaves

61.5 Server content inside a Client Component: children

  • Importing a Server Component into a client file turns it into a client component too.
  • Instead, pass it as children: the server renders it and the Client Component only receives the ready result.
  • The Client Component (Reveal) has no idea what is inside; clicking just shows the ready children.
React (TSX)
// app/Reveal.tsx"use client";import { useState } from "react";import type { ReactNode } from "react";type Props = { children: ReactNode };export function Reveal({ children }: Props) {  const [open, setOpen] = useState(false);  return (    <div>      <button onClick={() => setOpen(!open)}>        {open ? "Hide" : "Show reviews"}      </button>      {open && children}    </div>  );}
React (TSX)
// app/page.tsximport { Reveal } from "./Reveal"; async function Reviews() {  const list = ["Great course", "So clear"];  return list.map((r) => <p key={r}>{r}</p>);} export default function Page() {  return (    <Reveal>      <Reviews />    </Reveal>  );}
Output
[button] Show reviews (after click)[button] HideGreat courseSo clear

61.6 Props rule: must be serialisable

  • Props going from a Server Component to a Client Component travel over the network, so they must be serialisable.
  • OK: strings, numbers, booleans, plain objects, arrays (and JSX as children).
  • Not OK: functions such as an onLike event handler.
React (TSX)
import { LikeButton } from "./LikeButton"; export default function Page() {  function onLike() {    console.log("liked");  }  return <LikeButton onLike={onLike} />;}
Output
$ npm run dev⨯ Error: Event handlers cannot be passedto Client Component props.  <... onLike={function onLike}>If you need interactivity, considerconverting part of this to a Client Component.
  • Fix: write the click logic inside the Client Component, or use a Server Action (covered in the Server Actions video).

61.7 How hydration works

Hydration on first load
  1. 1.Server renders Server AND Client Components to HTML

  2. 2.Browser shows that HTML instantly

  3. 3.JS for the Client Components loads

  4. 4.React attaches click handlers and state to the same HTML (hydration)

  5. 5.If server HTML != first browser render -> hydration error

61.8 Comparison: Server vs Client Component

PointServer ComponentClient Component
How to createDefault, no directive"use client" at top of file
Where it runsOnly on the serverPre-rendered on server, then hydrated in the browser
async / await dataYes, can be asyncNo async component; fetch in effects or receive props
useState, useEffect, onClickNot allowedAllowed
DB access, secret keysYes (use server-only)Never
JS sent to browserNoneYes, the file and its imports

61.9 Common mistakes

  • Putting "use client" on the whole page instead of the small interactive leaf.
  • Passing a function prop from a Server to a Client Component.
  • Using a value that differs between server and browser during render (new Date(), Math.random()): hydration mismatch.
  • Next.js 16 catches this at build time with an error about an unstable value like new Date in a Client Component.
React (TSX)
// Wrong: server and browser times differ"use client"; export function Clock() {  const now = new Date().toLocaleTimeString();  return <p>Time: {now}</p>;}
React (TSX)
// Right: time is set only in the browser, after hydration"use client";import { useEffect, useState } from "react"; export function Clock() {  const [time, setTime] = useState("");  useEffect(() => {    setTime(new Date().toLocaleTimeString());  }, []);  return <p>Time: {time}</p>;}
  • Myth: you need "use server" to make a Server Component. Wrong: Server Components are the default; "use server" is for Server Functions.
  • Myth: "use client" means browser only. Wrong: its HTML is also built on the server on first load.

61.10 Best practices

  • Server Component by default; add "use client" only for state, effects, event handlers or browser APIs.
  • Push "use client" down to the leaves and always pass serialisable props.
  • Import the server-only package in code that touches the database or secrets so it can never slip into the client bundle.
  • Pass server content into a Client Component through children.

61.11 Interview tips

  • In the App Router the Server Component is the default: runs only on the server, can be async, sends zero JS.
  • A Client Component is created with "use client"; it is pre-rendered on the server and hydrated in the browser for state and events.
  • Mention the boundary: everything imported by a client file becomes client code, so keep it low.
  • Props across the boundary must be serialisable; server content goes in via children.
  • Hydration errors come from render output that differs between server and browser; move such values into useEffect.