Sub topic 4
How the Server Renders a Tree for the Client
This chapter assumes you know React components, props and JSX, async/await, and the idea that a React element is a plain object describing UI. It also assumes you have seen the Server Component and Client Component split from the earlier chapters. Here you will follow what the server does to turn a component tree into the output the browser receives.
The goal of the render pass
A normal React render calls your component functions and builds a tree of elements. A server render in an RSC framework does the same thing, with one difference. The server does not run the whole tree to completion. It runs only the Server Components, and it stops at every Client Component.
The output is not HTML and not JavaScript for the server parts. It is a serialized description of the tree, called the RSC payload. This chapter covers how the server produces that description. The next chapter covers how to read it.
The renderer's job can be stated in one sentence. It takes an element, resolves it until only things the client can understand remain, and writes those things out.
What the renderer does with each kind of element
The renderer visits each element in the tree and decides what to do based on its type.
| Element type | What the server renderer does |
|---|---|
| A string such as `"div"` or `"h1"` | Keeps it as is and renders its children. |
| A Server Component function | Calls it with its props, then renders whatever it returns. The function itself never leaves the server. |
| An async Server Component | Calls it, awaits the returned promise, then renders the result. |
| A Client Component (from a `"use client"` module) | Does not call it. Writes a reference to the module plus the props. |
| `Suspense` | Renders the children. If a child is not ready, writes the fallback first and the content later. |
| A string, number or `null` as a child | Writes the value directly. |
Two points matter most here.
- Server Components are expanded away. After the renderer calls a Server Component, only its output remains in the result. The client never sees the component's name, its code, or its imports.
- Client Components are left as holes. The renderer does not execute them. It records which module they live in and what props they received. The browser fills the hole in later.
Walking through a real tree
Take the first two code examples from this chapter's plan. The page is an async Server Component, and it renders a Client Component.
// app/page.js (Server Component by default in an RSC framework)
import Counter from './Counter';
async function getPosts() {
const res = await fetch('https://example.com/api/posts');
return res.json();
}
export default async function Page() {
const posts = await getPosts();
return (
<main>
<h1>Posts</h1>
<ul>
{posts.map((p) => (
<li key={p.id}>{p.title}</li>
))}
</ul>
<Counter initial={posts.length} />
</main>
);
}// app/Counter.js
'use client';
import { useState } from 'react';
export default function Counter({ initial }) {
const [count, setCount] = useState(initial);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}The renderer works through this in order:
- The framework asks the renderer to render
<Page />. Pageis a Server Component, so the renderer calls it. The function hitsawait getPosts()and the render of this branch pauses until the fetch resolves.Pagereturns a<main>element. The renderer writesmain, then descends into its children.h1andulare host elements. The renderer expandsposts.map(...)intolielements with the post titles as text.<Counter initial={3} />has a type that is a client reference. The renderer does not callCounter. It writes a reference toapp/Counter.jsand the prop{ initial: 3 }.
If the API returned one post titled "First post", the output looks like this. The text is simplified and illustrative, and the row syntax differs between React versions and frameworks.
1:I["app/Counter.js",["chunk-counter.js"],"default"]
0:["$","main",null,{"children":[["$","h1",null,{"children":"Posts"}],["$","ul",null,{"children":[["$","li",null,{"children":"First post"}]]}],["$","$L1",null,{"initial":1}]]}]Notice what is missing. There is no Page function, no getPosts, and no fetch URL. The Counter row is only a pointer, and "$L1" in row 0 marks where it plugs in.
The sequence of events
The render pass runs inside the server's request handling. The following diagram shows one request.
Order, pausing and waterfalls
The renderer walks the tree depth first, and it handles await per branch. When one async component is waiting, React can keep working on its siblings. The waterfall problem shows up inside a single component, not across siblings.
This component fetches two things in sequence:
async function getUser(id) {
const res = await fetch(`https://example.com/api/users/${id}`);
return res.json();
}
async function getOrders(id) {
const res = await fetch(`https://example.com/api/users/${id}/orders`);
return res.json();
}
export default async function Account({ id }) {
const user = await getUser(id);
const orders = await getOrders(id);
return (
<section>
<h2>{user.name}</h2>
<p>{orders.length} orders</p>
</section>
);
}The second request does not start until the first one finishes. If the calls are independent, start both before awaiting either:
export default async function Account({ id }) {
const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);
return (
<section>
<h2>{user.name}</h2>
<p>{orders.length} orders</p>
</section>
);
}A parent that awaits before rendering its children has the same effect. The children cannot start until the parent returns. Splitting data fetching into smaller async components, each wrapped in Suspense, lets them run in parallel. Chapter on Suspense covers that.
What a Server Component may and may not do
The render pass runs once per request, from top to bottom. It has no mounted instance, no browser and no re-render loop. That sets the rules.
- Allowed:
async/await, reading from databases or the file system, using secrets from environment variables, and importing server-only libraries. - Not allowed:
useState,useReducer,useEffect, event handlers such asonClick, and browser APIs such aswindoworlocalStorage. There is no state to update and no DOM to attach listeners to. - Allowed with limits: Props sent to a Client Component must be serializable. The next chapters cover which values qualify.
Because the output is written once and not re-run, a Server Component does not update on its own. New output comes from a new render pass, for example after navigation or after a Server Function runs.
Deduplicating work inside one pass
A single render pass can call the same data function from many components. React provides cache for Server Components so repeated calls with the same arguments in one pass share a result.
import { cache } from 'react';
export const getUser = cache(async (id) => {
const res = await fetch(`https://example.com/api/users/${id}`);
return res.json();
});The cache lasts for the duration of one request render. It is not a cross-request cache. Frameworks add their own caching layers on top, and those behave differently from framework to framework.
Errors during the render pass
An error thrown inside a Server Component does not crash the whole response when it can be contained. Which behaviour you get depends on where the error happens and on the framework.
- If the error occurs before any output is sent, the framework can return an error response.
- If it occurs after the first rows were streamed, the stream cannot be taken back. The renderer marks that part of the tree as failed, and the client shows the nearest error boundary.
- In production builds, error messages are usually replaced by a generic message and a digest, so server details are not leaked to the browser.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about `useState` or `useEffect` in a server file | A hook was used in a Server Component | Move the interactive part into a file marked `"use client"` |
| Page loads slowly, requests happen one after another | Sequential `await` calls for independent data | Use `Promise.all` or split into separate components under `Suspense` |
| Error about passing a function as a prop | A plain function crosses to a Client Component | Define it in the client file or use a Server Function |
| A secret appears in the browser | A value from the server was passed as a prop, so it was written into the payload | Pass only the fields the client needs |
| Client Component code seems to run on the server | It does run there for the HTML pass (SSR), but not in the RSC pass | See the chapter on RSC versus SSR |
Exercise
In the Page example, the server renders <Counter initial={posts.length} />. Does the server call the Counter function during the RSC render pass? What ends up in the payload for it, and why is useState safe inside Counter even though the server never runs it in that pass?
Show answer
No. Counter is a client reference, so the renderer does not call it. The payload gets a module row (module path, chunk list and export name) and an element with the "$L1" marker plus the props, here { initial: 3 } or whatever posts.length is. useState is safe because Counter runs only on the client, where React keeps component state. The server only needs to know which module to load and which serializable props to give it.
Exercise
A Server Component runs const a = await getA(); const b = await getB();, and the two calls do not depend on each other. Rewrite the line so both requests start at the same time, and state why the original was slow.
Show answer
Use const [a, b] = await Promise.all([getA(), getB()]);. In the original, getB() is not called until getA() has resolved, so the total time is the sum of both. With Promise.all, both promises start immediately and the total time is roughly that of the slower one.