Skip to content
Visual explainer 4h to learn 4 steps

Server vs client components

Decide what runs on the server and keep client bundles small.

By Invicly Tech, , in Frontend with React & Next.js. About 11 minutes to read.

Topic 21 of 36

In short

In the App Router, components are server components by default: they render on the server and send no JavaScript for themselves. Add 'use client' only for parts that need state, effects or browser APIs.

Explained simply

In the App Router, a component runs on the server unless you say otherwise. A server component can read a database or a secret key directly and send finished HTML to the browser. Its own code never travels to the user's device.

Some parts of a page must run in the browser: a button that counts clicks, a menu that opens, a form that reacts as you type. For those you write "use client" at the top of the file. That file becomes a client component, and its code is sent to the browser.

The goal is simple: keep as much as possible on the server, and make only the interactive pieces client components. Less JavaScript in the browser means faster loading, especially on cheap phones and slow networks.

The two kinds work together. A server page can fetch data and pass it as props to a small client button. The data travels as plain values, like text and numbers, so it must be something that can be turned into JSON-like data.

Press Play on a diagram to walk through it one step at a time.

LayersWhere each part runs
  1. 1
    Browser

    Hydrates client components and handles interaction

  2. 2
    Client components

    'use client': state, effects, event handlers

  3. 3
    Server components

    Default: fetch data, read secrets, render HTML

  4. 4
    Data sources

    Databases, APIs and files, reached only from server

CompareServer vs client components
Server component
  • Can be async and await data
  • Can use secrets safely
  • No JS shipped for itself
  • No useState or onClick
Client component
  • Marked with 'use client'
  • Uses state, effects, handlers
  • Code is sent to the browser
  • Still pre-rendered to HTML
CompareWhere to put the boundary
Too high
  • "use client" on page.tsx
  • Whole page and its imports ship
  • No direct database access
  • Large bundle, slower hydration
Just right
  • Page stays a server component
  • Only LikeButton has "use client"
  • Data fetched on the server
  • Tiny bundle for one button

In depth

What actually goes over the wire

When a request comes in, Next.js renders server components to a compact format called the React Server Component payload. It describes the finished UI: HTML-like elements, the props for each client component, and references to the JavaScript files those client components need. Next.js also turns it into HTML for the first load, so the user sees content before any JavaScript runs.

In the browser, React reads the payload, downloads only the client component code, and hydrates those parts, which means attaching event handlers to the existing HTML. Server components are never hydrated because they have no browser code. On later navigations, only the payload is fetched, not a full HTML page.

FlowFrom request to interactive page
  1. 1
    Server renders

    Server components run and fetch data

  2. 2
    RSC payload

    UI tree plus props for client components

  3. 3
    HTML

    Sent first so content shows fast

  4. 4
    Client JS loads

    Only code for "use client" components

  5. 5
    Hydration

    Client parts become interactive

"use client" is a boundary, not a label

The directive goes at the very top of a file and marks an entry point into the client bundle. Every module that file imports also becomes client code, even if those files have no directive. So marking a layout or page with "use client" pulls its whole import tree into the browser.

You only need the directive on the file where server code first hands over to client code. A component without it, imported from a client file, runs on the client too. Note that client components are still rendered to HTML on the server for the first load; "client" means their code also ships and runs in the browser. Use it when you need state, effects, event handlers, browser APIs like localStorage, or context.

  • Needs useState, useEffect or onClick: client
  • Uses window, localStorage or context: client
  • Reads a database or secret: server
  • Only renders data: server

Passing data and components across the boundary

Props from a server component to a client component must be serializable: strings, numbers, booleans, null, plain objects and arrays, Date, Map, Set, and promises. Functions cannot be passed, with one exception: server actions, which become references the client can call. Class instances lose their methods.

You can still put server components inside client components through composition. A client Tabs component can receive server-rendered content as children or as other props. The server renders those children first, and the client component only decides where to place them. This keeps heavy content, like a rendered markdown article, on the server while the tab switching runs in the browser.

MapServer content inside a client wrapper
page.tsx (server)
  • Tabs (client)
    • children: Article (server)
    • children: Comments (server)
  • LikeButton (client)
    • initial={42} is a plain number
  • Footer (server)

Keeping secrets on the server

Server components can read process.env.DATABASE_URL safely, because their code never ships. The risk is accidental imports: if a client component imports a file that reads a secret, the bundler may try to include it. Only environment variables prefixed with NEXT_PUBLIC_ are inlined into client code; others are empty there, which can cause confusing bugs.

Guard server-only modules by adding import "server-only" at the top of the file (install the server-only package). Any attempt to import that module from a client component then fails at build time with a clear error. Put your database client, auth helpers and data-access functions behind this guard.

Checking what you ship

Measure instead of guessing. In the browser, open DevTools, go to the Network tab, filter by JS, and reload: you see every script the page downloads and its size. The Coverage tab shows how much of that code actually runs. For a breakdown by package, use a bundle analyzer such as @next/bundle-analyzer, which draws a map of each chunk and the libraries inside it.

Typical findings: a date or chart library pulled into the client by a component that only formats data, or a whole page marked "use client" for one button. Fixes are moving that work to a server component, splitting the interactive part into its own small file, or loading a heavy widget only when needed with next/dynamic.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Explain server vs client components~1h
  2. 2
    Add 'use client' only where needed~1h
  3. 3
    Pass server data to client components~1h
  4. 4
    Check client bundle size~1h

Key points

  • 'use client' marks a boundary; everything it imports joins the client bundle.
  • Push 'use client' down to small leaf components like buttons and forms.
  • Server components can pass serialisable props, or render server components as children.
  • Never import server-only code like database clients into client components.

Key terms

Tap a card to flip it. 0/5 known

Examples

tsx
// app/page.tsx (server component)
import LikeButton from './like-button';

export default async function Page() {
  const post = await db.post.findFirst();
  return <h1>{post.title} <LikeButton initial={post.likes} /></h1>;
}

// app/like-button.tsx
'use client';
import { useState } from 'react';
export default function LikeButton({ initial }: { initial: number }) {
  const [likes, setLikes] = useState(initial);
  return <button onClick={() => setLikes(likes + 1)}>{likes}</button>;
}

Data loads on the server; only the button ships JavaScript.

Splitting a product page

The original page was fully client-side: it fetched in an effect and shipped a markdown library. Step 1: remove "use client" from the page and make it async. Step 2: fetch the product and render the markdown description on the server; the library never ships. Step 3: move the Add to cart button into its own client file that receives just the id and price. The browser now downloads only the button's code.

tsx
// app/products/[id]/page.tsx (server)
import { renderMarkdown } from "@/lib/markdown";
import { getProduct } from "@/lib/products";
import { AddToCart } from "./add-to-cart";

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const product = await getProduct(id);
  return (
    <article>
      <h1>{product.name}</h1>
      <div dangerouslySetInnerHTML={{ __html: renderMarkdown(product.description) }} />
      <AddToCart id={product.id} price={product.price} />
    </article>
  );
}

Protecting the database module

A teammate once imported the db helper into a client component, and the build tried to bundle the database driver for the browser. Step 1: install the server-only package. Step 2: import it at the top of lib/db.ts. Step 3: now any client import of lib/db fails the build with a clear message, before a secret or driver can leak.

ts
// lib/db.ts
import "server-only";
import { neon } from "@neondatabase/serverless";

const sql = neon(process.env.DATABASE_URL!);

export async function getProduct(id: string) {
  const rows = await sql`SELECT id, name, price FROM products WHERE id = ${id}`;
  return rows[0] ?? null;
}

Quick reference

  • Components are server components by default in the app directory
  • "use client" at the top of a file makes it and everything it imports client code
  • Client components are still pre-rendered to HTML on the server
  • Props across the boundary must be serializable; functions are not (except server actions)
  • Pass server components to client components as children to keep them on the server
  • import "server-only" makes client imports of a module fail at build time
  • Only NEXT_PUBLIC_ environment variables are available in client code
  • Check JS size in DevTools Network (filter JS) or with @next/bundle-analyzer

Common mistakes

  • Putting 'use client' at the top of a whole page and shipping everything.
  • Passing functions or class instances from server to client components as props.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A file without "use client" is imported by a client component. Where does its code run?

Question 2

2Which prop can a server component NOT pass to a client component?

Question 3

3Are client components rendered on the server at all?

Question 4

4What does import "server-only" do?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    A page shows a list of posts and one Subscribe button with a click counter. Decide which component is server and which is client, and write the directive in the right file.

  2. Exercise 2medium

    Build a client Collapsible component that toggles open and closed, and use it from a server page to wrap server-rendered content.

  3. Exercise 3hard

    A dashboard page has "use client" at the top because of one date picker, and it imports a large charting library to draw static charts. Plan the refactor to cut the client bundle and list the steps.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do server components replace API routes?
For reading data in your own pages, mostly yes: fetch directly in the server component. You still need route handlers for webhooks, mobile apps and other external clients.
Can I use useState in a server component?
No. Hooks with state or effects, and event handlers, only work in client components. Move the interactive part into a small "use client" file.
Is "use client" bad for SEO?
No. Client components are still rendered to HTML on the server for the first load. The cost is extra JavaScript, not missing content.

Go deeper

ShareXLinkedInWhatsApp