Sub topic 6
Fine-grained and conditional memoization
The previous chapters covered what the React Compiler does and how the Rules of React make it safe. This chapter covers the granularity of the memoization it produces, and why that granularity goes beyond what memo, useMemo and useCallback can do by hand. It assumes you know how hooks work, how React compares dependencies with Object.is, and why a new object or function identity on each render defeats memo.
Memoization per value, not per component
React.memo works at one level. It decides whether a whole component re-renders, based on a shallow comparison of its props. useMemo and useCallback work on single values, but you must place them by hand, and each one needs a dependency array you maintain yourself.
The compiler works at the level of reactive scopes. A reactive scope is a group of statements that produce one or more values from the same set of inputs. The compiler:
- Finds every value created during render, including JSX elements, objects, arrays and functions.
- Works out which props, state and other values each one depends on.
- Groups values that must be recomputed together into a scope.
- Wraps each scope in a check that skips the work when none of its inputs changed.
The result is many small caches inside one component instead of one decision about the whole component.
Applying this to the `List` component
Take the compiler-friendly version of the list from earlier in this tutorial:
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 reaches roughly these conclusions:
visibledepends onitemsandquery. Selecting a row changes onlyselectedId, so the filter does not run again.handleSelectdepends only onsetSelectedId. React guarantees that a state setter keeps the same identity between renders, so the compiler can treathandleSelectas stable.- The
<p>element depends only onselectedId. - The array of
<Row>elements depends onvisibleandhandleSelect. When you type in the input,visiblechanges, so the array is rebuilt. When you select a row,visibleandhandleSelectare unchanged, so the same element objects are reused.
Because React skips rendering a child when it receives the exact same element object, Row does not re-render on a selection change. That gives you the effect of memo(Row) without wrapping it. The compiler even covers the case where Row is imported from a library you do not control, because it memoizes the element created in your component and not the child itself.
What the output looks like
The compiler does not emit useMemo calls. It uses a cache array that React allocates once per component instance. The code below is a simplified sketch of the shape of the output for a small component. Real output differs in variable names and slot layout, so treat it as an illustration and not as the exact result.
import { c as _c } from 'react/compiler-runtime';
function Greeting({ name, count }) {
const $ = _c(4); // four cache slots for this component
let heading;
if ($[0] !== name) {
heading = <h1>Hello, {name}</h1>;
$[0] = name;
$[1] = heading;
} else {
heading = $[1];
}
let badge;
if ($[2] !== count) {
badge = <span>{count} new</span>;
$[2] = count;
$[3] = badge;
} else {
badge = $[3];
}
return (
<div>
{heading}
{badge}
</div>
);
}Each if compares the stored input with the current one using Object.is. On a match, the cached output is reused. Otherwise the value is rebuilt and the slots are updated. Changing count rebuilds only the badge, and the heading element stays identical.
Conditional memoization
The Rules of Hooks forbid calling hooks after an early return or inside a branch. That limits manual memoization. If a component returns early, every useMemo has to sit above the return, even when the value is needed only in the other branch.
import { useState } from 'react';
function formatPrice(product) {
return `${product.currency} ${product.price.toFixed(2)}`;
}
export function ProductCard({ product, onAdd }) {
const [qty, setQty] = useState(1);
if (!product.inStock) {
return <p>{product.name} is sold out</p>;
}
// With manual memoization, a useMemo here would break the Rules of Hooks.
const price = formatPrice(product);
const total = product.price * qty;
return (
<section>
<h2>{product.name}</h2>
<p>{price}</p>
<label>
Quantity
<input
type="number"
min="1"
value={qty}
onChange={(e) => setQty(Number(e.target.value))}
/>
</label>
<p>Total: {total}</p>
<button onClick={() => onAdd(product.id, qty)}>Add to cart</button>
</section>
);
}The compiler memoizes the work after the early return. It does so by emitting cache checks instead of hook calls, so the call order of hooks is untouched. In this example price depends only on product, so changing the quantity does not recompute it. The same holds for values created inside an if block or a ternary branch. Those values are cached under their own conditions and no longer need to be hoisted above the branch.
The hook call itself, useState, still has to run on every render before the return. The compiler does not change the Rules of Hooks, and it still reports violations.
Manual and automatic memoization compared
| Aspect | `memo`, `useMemo`, `useCallback` | React Compiler |
|---|---|---|
| Unit of caching | A component, or one value you chose | Each reactive scope in the component |
| Dependencies | Written by hand in an array | Inferred from the code |
| After an early return | Not allowed (hooks) | Allowed |
| Inside a conditional branch | Not allowed (hooks) | Allowed |
| Wrong dependency list | Stale values or no benefit | Not possible, because dependencies are derived |
| Child components you cannot edit | Cannot wrap them | The element you create is cached |
Where fine-grained memoization stops
The compiler is precise, but it cannot cache across a boundary it does not control. Several cases are worth knowing.
Mutated values form one scope
If a value is created and then mutated, the compiler must treat the creation and the mutations as one unit, because it cannot cache the half-built value. Two objects that are mutated together, for example one added to the other, end up in the same scope and share the same inputs. Building an object in one expression often produces smaller scopes than building it through many mutating steps.
Unstable inputs cause cache misses
Comparison is shallow and uses Object.is. The compiler memoizes your component, but it cannot fix the identity of values passed in from outside. Suppose a parent is not compiled and passes style={{ color: 'red' }} on every render. Inside the child, a scope that depends on style sees a new object each time and rebuilds. Compile the parent too, or move the constant out of render.
Cheap values may not be cached
Comparing inputs and reading a slot has a cost. For trivial work, such as adding two numbers, caching may not pay for itself. Do not expect every expression to appear in the cache array.
It is an optimization, not a contract
React may discard cached values, and the compiler may group scopes differently between versions. Your code must produce correct results whether or not a value was cached. Do not rely on a cached value keeping its identity for program correctness, for example by using an object as a key in a WeakMap that must survive across renders.
Choosing what to write by hand
With per-value caching, your default should be to write plain code and let the compiler decide. Keep a manual useMemo or useCallback when you need a guarantee about identity, such as a value used as an effect dependency where the effect must not re-run. Later in this tutorial, the chapter on existing manual memoization covers that decision in more detail. For now, remember that adding useMemo around a value the compiler already caches does not hurt correctness, but it adds noise and a dependency array that you must keep accurate.
Exercise
In the ProductCard component above, the user changes the quantity input from 1 to 2 and the product prop stays the same object. Which values can the compiler reuse from its cache, and which must be recomputed? Why can a hand-written useMemo not cache price in that component?
Show answer
The compiler can reuse the price string (it depends only on product) and the <h2> element (it depends only on product.name). total depends on qty, so it is recomputed, and so are the elements that show it or use qty, such as the input, the total paragraph and the button handler. A hand-written useMemo for price would have to be placed after the if (!product.inStock) return ... early return, and hooks cannot be called after a conditional return. You would have to move it above the return and compute a price for products that are never displayed. The compiler avoids this because it emits cache checks, not hook calls.
Exercise
A compiled Dashboard component receives config={{ theme: 'dark' }} from a parent that is not compiled. Inside Dashboard, a scope builds a <Chart> element from config. Will that scope be reused between renders? What are two ways to fix it?
Show answer
No. The parent creates a new object on every render, so Object.is(prevConfig, config) is false and the scope rebuilds each time. Fix it by compiling the parent so the object literal is cached, or by moving the constant outside the component, for example const config = { theme: 'dark' }; at module level, so its identity never changes.