Sub topic 1
Recap: elements, components and the tree React renders
React Server Components change where parts of a React tree are rendered. They don't change what the tree is made of. The rest of this tutorial depends on a precise understanding of elements, components and the tree that React builds from them. This chapter rebuilds that understanding, and it pays extra attention to the idea that most of a React tree is plain data.
Prerequisites
This chapter assumes you already know the following:
- React components, props and JSX at a working level.
- Basic hooks such as
useStateanduseEffect. - Promises and
async/awaitin JavaScript. - The general difference between client-side rendering and server-side rendering.
- Basic familiarity with ES modules and bundlers.
You don't need any knowledge of Server Components yet. The code examples run in Node.js (version 18 or later) in a project with react installed and "type": "module" in package.json.
Elements are plain objects
JSX is syntax for calling createElement. This line:
<Greeting name="Ada" />compiles to a call equivalent to createElement(Greeting, { name: 'Ada' }). The call returns a React element, which is a plain JavaScript object that describes what you want on screen. An element does not draw anything, and it is not a DOM node. It is a description.
import { createElement } from 'react';
function Greeting({ name }) {
return createElement('p', { className: 'greeting' }, 'Hello, ', name);
}
const element = createElement(Greeting, { name: 'Ada' });
console.log(element.type === Greeting); // true
console.log(element.props); // { name: 'Ada' }
const host = createElement('p', { className: 'greeting' }, 'Hello, ', 'Ada');
console.log(host.type); // 'p'
console.log(host.props);
// { className: 'greeting', children: [ 'Hello, ', 'Ada' ] }An element has a small set of important fields:
| Field | Meaning |
|---|---|
| `type` | A string for a built-in element such as `'p'`, or a function (or class, or special object) for a component. |
| `props` | An object holding every prop, including `children`. |
| `key` | An optional identity hint used when React compares lists. |
| `ref` | An optional handle to the rendered node. In React 19 it is passed as a normal prop on function components. |
| `$$typeof` | An internal marker that tells React the object really is an element. |
The real object also carries development-only fields, so a console.log of an element shows more than the table does. The table covers the fields you will see in the payload later in this tutorial.
Elements are treated as immutable. You never change element.props. When something changes, you create a new element. This is what makes elements cheap to produce and easy to compare.
Element types: strings and functions
The type field decides how React handles an element.
- A string type such as
'ul'is a host element. React will ask the environment (the DOM in a browser) to create a node of that kind. - A function type such as
Greetingis a component. React will call it withpropsand use the element, or elements, it returns.
This difference matters a lot later. A string type can be written down as text. A function type is code, and code cannot be sent across a network as ordinary data.
Components are functions from props to elements
A component is a function that takes props and returns something React can render: an element, a string, a number, null, an array of these, and a few other things.
function Item({ label }) {
return <li>{label}</li>;
}
function List({ items }) {
return (
<ul>
{items.map((item) => (
<Item key={item} label={item} />
))}
</ul>
);
}Calling List does not produce HTML. It produces an element whose type is 'ul'. That element's children are elements whose type is the Item function. Nothing has called Item yet.
The component function is not the element
Beginners and experienced developers both mix up three things, so keep them apart:
- The component is the function, such as
Item. You write it once. - The element is an object like
{ type: Item, props: { label: 'a' } }. You create many of them. - The instance is React's internal record of one mounted use of that component, which holds its state and effects. You never touch it directly.
When you write <Item label="a" />, React does not call Item at that moment. It builds an element. Calling Item happens later, when React renders the element.
Rendering expands the tree
Rendering is the process of calling component functions until the whole description is made only of host elements and text. React starts with a root element, calls its function, looks at the elements that come back, and repeats for each function-typed child.
The following small program does the same thing in about twenty lines. It is a teaching model, not a real renderer. It ignores hooks, fragments, context and many other features.
import { createElement } from 'react';
function expand(node) {
if (node === null || node === undefined || typeof node === 'boolean') {
return null;
}
if (typeof node === 'string' || typeof node === 'number') {
return String(node);
}
if (Array.isArray(node)) {
return node.map(expand);
}
const { type, props } = node;
if (typeof type === 'function') {
return expand(type(props));
}
const { children, ...rest } = props;
return { tag: type, props: rest, children: expand(children) };
}
function Item({ label }) {
return createElement('li', null, label);
}
function List({ items }) {
return createElement(
'ul',
null,
items.map((item) => createElement(Item, { key: item, label: item }))
);
}
const tree = expand(createElement(List, { items: ['a', 'b'] }));
console.log(JSON.stringify(tree, null, 2));The output is a tree of host nodes only:
{
"tag": "ul",
"props": {},
"children": [
{ "tag": "li", "props": {}, "children": "a" },
{ "tag": "li", "props": {}, "children": "b" }
]
}Notice the structure of expand. When type is a function, the function is called and its result is expanded again. When type is a string, the node is kept and only its children are expanded. This recursion is the core of rendering. Real React adds scheduling, state and many more node kinds, but the shape of the work is the same.
The tree and what React keeps between renders
React keeps an internal tree of the mounted components and host nodes. It is often called the fiber tree. Each render produces a new element tree. React then compares it with the previous one and applies only the differences to the real DOM. This comparison is called reconciliation.
Reconciliation follows two rules that you use every day:
- If the
typeat the same position is the same, React keeps the existing instance and its state, and updates the props. - If the
typediffers, React destroys the old subtree and mounts a new one. State inside the old subtree is lost.
The key is how React matches items in a list across renders. A stable key such as a database id keeps state attached to the right item. An array index used as a key breaks that match when items are reordered or removed.
This position-and-type rule explains a behavior that becomes important when a router replaces a tree on navigation. State survives only where the new tree has the same types in the same places.
Common mistakes
- Calling a component as a function. Writing
Item({ label: 'a' })inside another component runsItemin the parent's render. Hooks insideItemthen attach to the parent. Use<Item label="a" />so React controls the call. - Mutating an element or its props.
element.props.label = 'b'is wrong. Props are read-only, and React may warn or freeze the object in development. - Defining a component inside another component. Each render creates a new function, so the
typediffers on every render. React sees a different type and remounts the subtree, which loses its state. - Expecting a rendered object to be a DOM node. Elements have no
.style,.focus()or.innerHTML. Those belong to DOM nodes, which exist only after React commits the result. - Rendering a plain object as a child.
<div>{{ a: 1 }}</div>throws, because an object that is not an element or an iterable is not a valid child.
Why this recap matters for Server Components
Look again at the data you have seen in this chapter. An element is an object with a type, props and children. The type is a string for host elements, and it is a function for components. The props are values that you pass in.
If a component function can run on a server, the server can produce this same element tree. Every piece that is a string, a number, a list or a plain object can be written to a stream of text. The only piece that is hard to write down is a function-typed type. A server can call a function it owns and replace it with the result. It cannot send a function that has to run in the browser.
Much of the design of Server Components follows from that point. The next chapters cover which components run where, how the server writes the tree out, and how the output points at code that must run in the browser.
Exercise
A parent component renders <Item label="a" /> once. Which of these happens during the parent's render: (1) the Item function is called, or (2) an element with type: Item and props: { label: 'a' } is created? What decides when Item is actually called?
Show answer
Only (2) happens during the parent's render. The JSX creates a plain element object that refers to the Item function in its type field. React calls Item later, when it renders that element as part of expanding the tree. Because React makes that call, hooks inside Item attach to Item's own instance.
Exercise
A component Page declares function Row() { ... } inside its own body and renders <Row />. Each time Page re-renders, the state inside Row resets. Why does this happen?
Show answer
Each render of Page creates a new Row function, so the element's type is a different function from the previous render. Reconciliation sees a changed type at the same position, destroys the old subtree and mounts a new one, so the state is lost. Moving Row outside Page keeps the type stable.