Sub topic 5
What compiled output looks like
This chapter assumes you know function components, props, useState, useMemo and useCallback. It also assumes you have read the earlier chapters on the Rules of React and what the compiler does. Here you will look at the code the React Compiler emits, learn to read it, and see why it keeps your components' behavior the same.
The compiler rewrites functions, not behavior
The compiler is a Babel plugin. It reads a component or hook, builds an internal model of how values flow through it, and writes back a function that does the same work with a cache. Your source files are not changed. Only the build output contains the rewritten code.
The internal model is the important part. The compiler does not search for useMemo calls. It converts each function into a control-flow representation and works out which values depend on which others. It also tracks which values can be mutated and where. Values that change together are grouped into a reactive scope. A reactive scope is a block of code that only needs to run again when one of its inputs changes.
A first example
Start with a very small component:
function Greeting({ name }) {
const label = name.toUpperCase();
return <h1>{label}</h1>;
}Run it through the compiler and you get something close to this. The exact variable names and layout change between compiler versions, so treat it as an illustration.
import { c as _c } from "react/compiler-runtime";
function Greeting(t0) {
const $ = _c(4);
const { name } = t0;
let t1;
if ($[0] !== name) {
t1 = name.toUpperCase();
$[0] = name;
$[1] = t1;
} else {
t1 = $[1];
}
const label = t1;
let t2;
if ($[2] !== label) {
t2 = <h1>{label}</h1>;
$[2] = label;
$[3] = t2;
} else {
t2 = $[3];
}
return t2;
}Read it in four parts:
_c(4)comes fromreact/compiler-runtime. It returns an array with four slots that React keeps for this component instance. By convention the compiler names it$.- Each cached computation becomes an
ifblock. The block compares the inputs saved in earlier slots with the current inputs, using!==. - If an input changed, the block recomputes the value and stores the new inputs and the new result. Otherwise it reads the saved result from the cache.
- The JSX is cached too. When
labelis unchanged, the component returns the same element object as last time. React sees an identical element reference and can skip work below it.
Compare this with useMemo. A dependency array lists the inputs, and React compares them. Here the compiler writes the comparison itself, and it derived the inputs from the code.
Tracking the cache by hand
The number passed to _c is the total count of slots used by the function. In Greeting there are two scopes with one input and one output each, so four slots are used.
| Slot | Holds | Used by |
|---|---|---|
| `$[0]` | last `name` | first scope's input check |
| `$[1]` | last `label` source value | first scope's cached result |
| `$[2]` | last `label` | second scope's input check |
| `$[3]` | last JSX element | second scope's cached result |
A scope with several inputs uses one slot per input, plus one slot per output. A scope with no inputs uses a single slot, as the next section shows.
Values that never change
Now consider a scope that depends on nothing from props or state.
function Toolbar({ onSave }) {
const options = { dense: true, theme: "light" };
return <Menu options={options} onSave={onSave} />;
}Without memoization, options is a new object on every render. It would break memo on Menu, because the reference changes while the contents do not. The compiled output computes it once:
import { c as _c } from "react/compiler-runtime";
function Toolbar(t0) {
const $ = _c(3);
const { onSave } = t0;
let t1;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t1 = { dense: true, theme: "light" };
$[0] = t1;
} else {
t1 = $[0];
}
const options = t1;
let t2;
if ($[1] !== onSave) {
t2 = <Menu options={options} onSave={onSave} />;
$[1] = onSave;
$[2] = t2;
} else {
t2 = $[2];
}
return t2;
}The check === Symbol.for("react.memo_cache_sentinel") asks whether this slot has ever been filled. React initializes every cache slot with that sentinel value. Since options has no inputs, it is built on the first render only, and every later render returns the same object. This is the effect you would otherwise get from hoisting the object out of the component or from useMemo(() => ..., []).
Memoizing the example from the spine
The List component from the earlier chapters has a filtered list, a selection handler, and a Row child. Here is the version without manual memoization:
import { useState } from 'react';
function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
}
export function List({ items }) {
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState(null);
const visible = items.filter((i) => i.name.includes(query));
const handleSelect = (id) => setSelectedId(id);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<p>Selected: {selectedId}</p>
<ul>
{visible.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
))}
</ul>
</>
);
}The compiler finds these scopes:
visibledepends onitemsandquery. It is recomputed only when one of them changes.handleSelectdepends only onsetSelectedId, which React guarantees is stable. It is created once, soRowalways receives the sameonSelect.- The
<ul>with its mapped rows depends onvisibleandhandleSelect. It is rebuilt only whenvisiblechanges. - The
<input>depends onqueryandsetQuery. The<p>depends onselectedId.
When you select a row, selectedId changes but visible does not. The compiled component reuses the cached <ul> element, so no Row renders again. This is the behavior the memo, useMemo and useCallback version produced by hand.
Seeing the output yourself
You can inspect compiled code in two ways. The online React Compiler Playground at playground.react.dev shows the output next to your input. To run it locally, install the packages and use a short script:
// compile.mjs
// npm install --save-dev @babel/core babel-plugin-react-compiler
import babel from '@babel/core';
const source = `
function Greeting({ name }) {
const label = name.toUpperCase();
return <h1>{label}</h1>;
}
`;
const result = babel.transformSync(source, {
filename: 'Greeting.jsx',
babelrc: false,
configFile: false,
parserOpts: { plugins: ['jsx'] },
plugins: [['babel-plugin-react-compiler', {}]],
});
console.log(result.code);Run it with node compile.mjs. The parserOpts line lets Babel parse JSX without a preset that would turn the JSX into function calls. That keeps the output readable.
What the compiler can do that hooks cannot
Hand-written memoization has limits that the compiled form does not share.
- After an early return. Hooks must be called unconditionally, so you cannot call
useMemoafterif (!user) return null;. The compiler memoizes whatever comes after the return, because it generates plainifblocks rather than hook calls. - Inside conditions and loops. The compiler can cache a value that is computed in only one branch.
- At finer grain than a hook. One
useMemocaches one value. The compiler splits a function into many scopes, so a change toquerydoes not invalidate the cache for unrelated JSX.
Here is the early-return case:
function Profile({ user, theme }) {
if (!user) return null;
const initials = user.name
.split(' ')
.map((part) => part[0])
.join('');
return <Avatar initials={initials} theme={theme} />;
}initials depends only on user.name, and the compiler caches it even though the function can return earlier. Doing the same with useMemo would force you to restructure the component.
Why the Rules of React matter here
The $[0] !== name check is only valid if name really determines the result. This is why the compiler depends on the Rules of React. If you mutate a prop during render, the cached value can become stale because the input comparison no longer reflects what happened. Here is the mutating version from the earlier chapter:
function Bad({ items }) {
items.sort();
return <ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>;
}The compiler detects this mutation of a value it does not own and skips the component. The component then runs as ordinary React code, with no cache. A correct version copies first, as in [...items].sort(). Skipping is safe, but you lose the optimization, and a later chapter covers how to find skipped components.
Common misreadings
- "The cache is shared between components." It is not. Each component instance has its own cache array, kept by React, so two
Greetingelements never share slots. - "The cache survives unmounting." It does not. When an instance unmounts, its cache goes with it.
- "Compiled components never re-render." They still re-render when state or props change, or when a parent re-renders and passes new values. What changes is how much work happens inside each render and whether children can skip theirs.
- "The output proves the code is faster." It proves the code is cached. Measure with the React DevTools Profiler to see whether it matters for your app.
Exercise
In the compiled Toolbar output, why does the check for options compare $[0] with Symbol.for("react.memo_cache_sentinel") instead of comparing it with an input value? What would a caller of Menu notice if the compiler did not cache options?
Show answer
options is built from literals and has no inputs, so there is nothing to compare. The only question is whether the slot has been filled before, and the sentinel is the value React puts in every empty slot. Without the cache, options would be a new object on every render. A memoized Menu would see a changed options prop each time and re-render, even though the contents never changed.
Exercise
Suppose Greeting receives the same name on two renders in a row. Which slots does the compiled function read and which does it write on the second render?
Show answer
It reads $[0] to compare with name, then reads $[1] to get the cached uppercase value. The value of label is the same as before, so it reads $[2] to compare, then reads $[3] to return the cached <h1> element. It writes nothing, because both if blocks take the else branch.