Sub topic 1
Recap: Elements, Components, and the Tree React Renders
Prerequisites
This chapter assumes you know React components, JSX, props, basic hooks, async/await, and the difference between client-side and server-side rendering.
Elements and the React tree
A React element is a description of UI. JSX creates these descriptions. When elements contain other elements, they form a component tree.
function Page() {
return (
<main>
<h1>Posts</h1>
<Counter initial={0} />
</main>
);
}The tree has Page at its root. Its children are main, h1, and Counter. React uses this structure to decide what to render and update.
Server Components and Client Components
A Server Component runs only on the server. It can read server-side data directly and does not add its component code to the browser’s JavaScript bundle.
A Client Component runs in the browser. It can use state, effects, and event handlers. It must receive data that can cross the server-to-client boundary.
// app/page.js: Server Component
import Counter from './Counter';
export default async function Page() {
const response = await fetch('https://example.com/api/posts');
const posts = await response.json();
return (
<main>
<h1>Posts</h1>
<Counter initial={posts.length} />
</main>
);
}// app/Counter.js: Client Component
'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 `"use client"` boundary
"use client" is a module directive. It marks that module, and its imported client-side dependencies, as part of the client component graph. Place it at the smallest boundary that needs interactivity. A larger boundary can send more JavaScript to the browser.
How the server renders a tree
The server executes Server Components and produces an RSC payload. This payload is a serialized description of the rendered tree. It is not HTML and does not contain the implementation code for Server Components. Frameworks can use the payload with server-rendered HTML to make the page interactive.
Reading the RSC payload
A simplified payload might look like this:
1:I["app/Counter.js",["chunk-counter.js"],"default"]
0:["$","main",null,{"children":[["$","h1",null,{"children":"Posts"}],["$","$L1",null,{"initial":1}]]}]Row 0 describes the element tree. $L1 is a lazy reference to the client component declared in row 1. The browser loads that client module and uses the serialized initial prop.
Exercise
Why does the server send a reference to Counter instead of Counter's implementation?
Show answer
Counter is a Client Component, so the browser needs its bundled module to run state and event handlers.