Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 132 ยท Routing and Apps

Server Components, Server Functions and Frameworks

Understand React Server Components, the use client and use server directives, server functions, the RSC payload and when you need a framework such as Next.js - with runnable stand-ins.

Until now every component in this tutorial ran in the browser. That is the original React model: the server sends an almost empty HTML page plus a JavaScript bundle, the browser downloads and runs the bundle, and only then do users see content. It is simple, but it means users download code for everything (even the parts that never change), data is fetched in a second round trip after the code arrives, and nothing secret can ever be touched by a component.

React Server Components (RSC) change where components run. Some components run only on the server, ahead of time or per request. They can read a database or a file directly, and they send the browser just their output, not their code. Other components, the familiar interactive kind, still run in the browser. React 19 made Server Components and Server Functions a stable part of React for frameworks and bundlers to build on.

This lesson explains the mental model, the two directives ("use client" and "use server"), what crosses the network, and when a framework becomes necessary. The editor in this tutorial runs plain browser modules, so real Server Components cannot run here. Instead you get hand-written stand-ins that behave like the real thing at a small scale, which is the best way to understand what the framework does for you. Server-only code is shown in clearly labelled read-only blocks.

Server Components need a bundler and a server integration. React gives you the primitives; a framework (Next.js App Router, or other frameworks and bundlers adding RSC support) wires them up. You usually do not set RSC up by hand, so treat this lesson as understanding rather than setup instructions.

Two kinds of components

In a framework that supports RSC, a component is a Server Component by default. The other kind, a Client Component, is marked by putting "use client" at the top of its file.

Server Component Client Component
Runs On the server only (at build time or per request) On the server for the first HTML, then in the browser
Can be async and await data Yes No (use use() with a promise, or a library)
Can read databases, files, secrets Yes No (all of its code reaches the browser)
Can use useState, useEffect, event handlers No Yes
Can use browser APIs (window, localStorage) No Yes (in effects and handlers)
Code sent to the browser None Yes, in the bundle
Re-renders in the browser Never; new output comes from a server round trip Yes, whenever its state or props change

The names confuse people, because Client Components are also rendered on the server once, to produce the first HTML (see Server-Side Rendering and Hydration). The real difference is that Client Components additionally ship their code to the browser and keep running there. Server Components never do.

A Server Component looks like a normal function that happens to be async:

JSX
// app/products/page.jsx  (read-only sketch: needs an RSC framework such as Next.js)
import { db } from '@/server/db';
import { LikeButton } from './LikeButton';

export default async function ProductsPage() {
  const products = await db.query('select id, name, likes from products order by name');
  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.name} <LikeButton productId={product.id} initialLikes={product.likes} />
        </li>
      ))}
    </ul>
  );
}
JSX
// app/products/LikeButton.jsx  (read-only sketch)
'use client';

import { useState } from 'react';

export function LikeButton({ productId, initialLikes }) {
  const [likes, setLikes] = useState(initialLikes);
  return (
    <button type="button" onClick={() => setLikes(likes + 1)}>
      {likes} likes
    </button>
  );
}

ProductsPage queries the database directly. There is no API route, no useEffect, no loading flag, and the database library never reaches the browser. LikeButton is interactive, so it is a Client Component. The page is a tree where the server owns the static skeleton and the browser owns the small interactive islands.

What really crosses the network

When a Server Component renders, React does not send HTML only. It sends a compact, streamable description of the tree called the RSC payload (the format is named Flight). It contains:

  • the output of Server Components, already resolved into plain elements (ul, li, text),
  • references to Client Components (a module id plus the props to give them),
  • placeholders for parts that are still loading (Suspense boundaries).

The browser's React reads the payload, builds the tree, and loads only the Client Component code it references. When something changes on the server (a navigation, a refresh after a mutation), React fetches a new payload and merges it into the existing tree, keeping client state (like a half-typed input) intact.

You can recreate the idea in about forty lines. In the next example, renderToTree plays the server: it calls components (awaiting async ones), expands them until only HTML tags and Client Component references are left, and produces plain data. Hydrate plays the browser: it turns that data back into React elements and renders them. The JSON printed above the result is the stand-in for the payload.

A hand-made Server Component renderer

Look at the JSON: ProductList and Page are gone. Only section, h3, ul, li and two references of the form {"client":"LikeButton", ...} remain, with the data the server fetched baked into the props (initialLikes). Click a like button: it updates instantly with no server call, because LikeButton really runs in the browser. (The real payload is a more compact streaming text format, not JSON, and production frameworks use React's own reader instead of toElement.)

The "use client" boundary

"use client" is not a property of one component; it marks a module boundary. Everything the file imports becomes part of the client bundle, and every component it renders runs in the browser. You place the directive as high as needed and as low as possible: only the interactive leaf, not the whole page.

Three rules to remember:

  1. The boundary follows imports, not the visual tree. If a Client Component imports another component file, that file is client code too, even without its own directive.
  2. Server Components can render Client Components, and pass them props. The reverse needs care: a Client Component cannot import a Server Component, because that would pull server code into the browser.
  3. A Client Component can still show server-rendered content passed as children or other props, because the server component is rendered first and its output is passed in. This is the composition trick:
JSX
// ThemePanel.jsx  (read-only sketch)
'use client';
import { useState } from 'react';

export function ThemePanel({ children }) {
  const [dark, setDark] = useState(false);
  return (
    <div className={dark ? 'dark' : 'light'}>
      <button type="button" onClick={() => setDark(!dark)}>Toggle theme</button>
      {children}
    </div>
  );
}
JSX
// page.jsx  (a Server Component, read-only sketch)
import { ThemePanel } from './ThemePanel';
import { SalesReport } from './SalesReport'; // async Server Component

export default function Page() {
  return (
    <ThemePanel>
      <SalesReport />
    </ThemePanel>
  );
}

The interactive panel wraps a report that queries the database. SalesReport never joins the client bundle. This is the same idea as children and composition, and it is the main technique for keeping the client bundle small.

Props must be serializable

Because Server Component output travels over the network, anything the server passes to a Client Component has to be serializable. Plain data (strings, numbers, booleans, null, arrays, plain objects), Date, Map, Set, promises and JSX are fine. Ordinary functions, class instances and DOM nodes are not, because there is nothing to send. (Server Functions are the special exception, covered below.) The helper below checks values the way you would reason about it:

What can cross the boundary

The practical consequence: pass data and let the Client Component own its handlers (onClick), or pass a Server Function when the click should run code on the server.

Server Functions

A Server Function is an async function marked with "use server" that runs on the server but can be called from the browser. The bundler replaces the function in the client bundle with a small stub that sends a request to the server; to your code it looks like calling a normal async function.

JSX
// app/comments/actions.js  (read-only sketch: needs an RSC framework)
'use server';

import { db } from '@/server/db';
import { getCurrentUser } from '@/server/auth';

export async function addComment(previousState, formData) {
  const user = await getCurrentUser();
  if (!user) return { error: 'Please sign in first' };

  const text = String(formData.get('text') ?? '').trim();
  if (text === '') return { error: 'Write something first' };
  if (text.length > 280) return { error: 'Keep it under 280 characters' };

  await db.insert('comments', { text, authorId: user.id });
  return { error: null };
}

When a Server Function is passed to a form's action, you get the form Actions from React 19 (see also useActionState). Frameworks call such functions Server Actions. The stand-in below shows the full round trip: the client form builds FormData, callServer "posts" it to a registry of functions, the "server" validates and stores it, and the state returned comes back to useActionState. Open the console to see the request log.

A Server Function round trip

Submit an empty comment, then a real one. The console shows lines like POST /_actions/addComment body: {"text":"hello"}. That is exactly the point to remember about Server Functions.

A Server Function is a public HTTP endpoint. Anyone can call it with any arguments, not only your form. Always authenticate the caller, check permissions (see Authentication and Authorization Patterns), validate and sanitize every argument, and never trust ids or roles sent by the client. Also remember the directive is "use server" for functions that run on the server. It is not the opposite of "use client"; marking a Server Component with it is a mistake.

Async data flowing into the browser with use()

A Server Component can start a request and pass the promise (not the result) to a Client Component, which reads it with use() inside a Suspense boundary. The server does not wait for the slow part before sending the rest of the page, so fast content appears first and the slow piece streams in later. The stand-in below mimics it with promises created outside render; see use() and Suspense for the full story.

Streaming pieces with Suspense

The name appears after a moment while the activity list is still loading. Each Suspense boundary resolves on its own. In a real RSC app the "pending" parts stay in the stream and the server fills them in when the data arrives.

What else React 19 added

Several React 19 features were designed together with Server Components, though they also work in plain client apps:

  • Actions and useActionState, useFormStatus, useOptimistic for mutations (form actions).
  • use() to read promises and context during render.
  • Document metadata: <title>, <meta> and <link> rendered anywhere in the tree are hoisted into <head>.
  • Ref as a prop, cleanup functions for ref callbacks, <Context value> and better error reporting.

Metadata hoisting is easy to see without a server:

Metadata hoisted into the head

The <title> JSX does not appear in the page body; React moves it to the document head and keeps it in sync. The console shows document.title is now: Tea | Demo shop, then Jam | Demo shop after you switch. In a server-rendered app this means every route component can set its own SEO tags next to the content they describe.

Frameworks: what they add and when you need one

React ships the renderer and the protocol. Everything else that makes a full application is up to you or a framework:

Need What a framework provides
Routing and layouts File-based or configured routes, nested layouts, loading and error files
Server rendering and RSC A server runtime, a bundler integration that splits client and server code
Data loading and caching Conventions for fetching on the server, cache control, revalidation
Mutations Server Actions or route actions wired to forms
Build and deployment Code splitting, image/font optimization, static export, edge/serverless targets

Next.js (App Router) is the most widely used implementation of Server Components: files such as page.tsx and layout.tsx are Server Components by default, "use client" opts out, "use server" creates Server Actions, and it adds caching and streaming. React Router (framework mode) and Remix, TanStack Start and others cover routing, loaders and SSR with their own models and are adding or exploring RSC support. Check each project's documentation for the current state, because this area moves quickly.

Do you need one? A rough guide:

  • A dashboard behind a login, mostly interactive, SEO irrelevant: a plain client app (Vite) is fine and simpler.
  • A public site, shop or blog where first load speed and search engines matter: use a framework with SSR or static generation.
  • Lots of read-only content with little interactivity: Server Components cut the JavaScript sent to users dramatically.
  • Your team has no backend yet: start client-side; moving to a framework later is a migration, so do not choose RSC just because it is new.

Server Components also come with trade-offs: a more complex mental model (two environments in one codebase), server infrastructure to run, and fewer libraries that work unchanged (anything using state, context or effects needs "use client").

Common mistakes

  • Adding "use client" to the page "to fix an error". Move the interactive part into a small client component instead, or you lose the benefits.
  • Importing a server-only module (database client, fs) into a file reachable from a Client Component. Use a server-only marker package or your framework's check so this fails at build time.
  • Passing functions, class instances or secrets as props to Client Components. Props sent to the client are visible to users.
  • Trusting arguments of a Server Function.
  • Fetching the same data in several Server Components without a shared cache; frameworks usually dedupe identical fetch calls in one render, but plain database calls need your own caching.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about a Server Component is true?

    Server Components run only on the server, so they can await data and use server resources. They have no state, effects or event handlers, and their code never reaches the browser.
  2. 2. What does the 'use client' directive mark?

    'use client' marks a module boundary in the import graph. It does not prevent the first server render; it means the code also runs in the browser.
  3. 3. A Server Component wants to give a Client Component a callback prop (a normal function). What happens?

    Props crossing the boundary must be serializable. Plain functions are not; only Server Functions have a way to be called remotely.
  4. 4. Why must you validate arguments and check permissions inside a Server Function?

    The framework exposes the function over HTTP. Treat it like any API route: authenticate, authorize and validate.
  5. 5. How can a Client Component display content produced by a Server Component?

    The server renders the Server Component and passes the result as props. The client component just places it, so the server code never joins the client bundle.

Summary

  • Server Components run only on the server and send their output (the RSC payload), not their code; Client Components also run in the browser and keep state.
  • "use client" marks a module boundary. Put it on small interactive leaves and pass server-rendered content through children.
  • Props crossing from server to client must be serializable: plain data, dates, maps, sets, promises and JSX are fine; ordinary functions and class instances are not.
  • "use server" creates Server Functions: async functions callable from the browser, usable as form actions. They are public endpoints, so authenticate, authorize and validate.
  • A promise passed to a Client Component and read with use() inside Suspense lets slow data stream in after fast content.
  • React 19 also added Actions, use(), metadata hoisting and ref improvements, which work in client-only apps too.
  • Real RSC needs a framework or bundler integration (such as Next.js App Router); choose one when SEO, first-load speed or server data access matter, and not just because it is new.

Next: Server-Side Rendering and Hydration