Sub topic 3
What the React Compiler Does
This chapter assumes you know function components, props and state, and the useState, useMemo and useCallback hooks. You should also know that React re-renders a component when its state changes or its parent re-renders. It builds on the previous chapters about re-renders and the cost of memoizing by hand.
The problem the compiler targets
React re-renders a component by calling it again. Each call creates new objects, arrays and functions. Two values with the same contents are still different references, so { a: 1 } === { a: 1 } is false.
That matters in two places:
- A child wrapped in
React.memoskips rendering only if every prop is the same reference as last time. A new inline function or object defeats it. - A hook such as
useEffectoruseMemore-runs when a dependency has a new reference, even if the contents are equal.
Manual memoization fixes this with memo, useMemo and useCallback. It works, but you must decide what to wrap, write correct dependency arrays, and keep both up to date as the code changes. A missing dependency causes stale values. An unnecessary one causes wasted work.
Here is the component from the earlier chapters, memoized by hand:
import { memo, useCallback, useMemo, useState } from 'react';
const Row = memo(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 = useMemo(
() => items.filter((i) => i.name.includes(query)),
[items, query]
);
const handleSelect = useCallback((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>
</>
);
}What the compiler is
The React Compiler is a build-time tool. It reads your component and hook source code, works out which values depend on which inputs, and rewrites the code so that values are reused when their inputs have not changed. It ships as a Babel plugin, babel-plugin-react-compiler.
Three points define its scope:
- It runs when you build, not in the browser. Users receive the already transformed JavaScript.
- It changes only components and hooks. It finds them by convention: functions whose names start with an uppercase letter and return JSX, and functions named
useSomethingthat call hooks. - It adds memoization. It does not change what your code means. If your code follows the Rules of React, the compiled version behaves like the original, but skips work.
With the compiler enabled, you can write the same component without any 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 caches visible so it is recomputed only when items or query changes. It also keeps handleSelect stable and reuses the JSX for each Row when its props are unchanged. So typing in the input does not re-render every row.
How it decides what to cache
The compiler analyzes the data flow inside each component. For every value it computes, such as a derived array, a callback or a piece of JSX, it records which props, state and other values it reads. At runtime, the compiled code compares those inputs with the ones from the previous render. If none changed, it returns the cached value. If any changed, it recomputes and stores the result.
This differs from useMemo in a few ways, which the table summarizes.
| Aspect | Manual memoization | React Compiler |
|---|---|---|
| Who picks what to cache | You | The compiler |
| Dependency lists | You write them | Derived from the code |
| Where it can apply | Anywhere you can call a hook | Anywhere in a component or hook, including after an early `return` |
| Runs when | At runtime, inside React | Memoization code is inserted at build time |
| Failure mode | Stale values or wasted work from wrong dependencies | The component is skipped if the compiler cannot prove it is safe |
The last row is important. The compiler does not guess. If it cannot prove that a component is safe to memoize, it leaves that component unchanged, so it behaves as before.
The Rules of React are the contract
The compiler assumes your components are pure during render: the same props, state and context produce the same output, and render does not mutate anything it does not own. Props and state must be treated as immutable. Side effects belong in event handlers and effects, not in the render body.
When code follows these rules, caching is safe, because skipping a call cannot change the result. When code breaks them, caching could produce wrong output. The compiler then skips the component, and the lint rules (covered in a later chapter) report the problem.
This example breaks the rules by mutating a prop, and shows the fix:
// Breaks the Rules of React: mutates a prop during render.
function Bad({ items }) {
items.sort();
return <ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>;
}
// Fixed: copy first, then sort the copy.
function Good({ items }) {
const sorted = [...items].sort();
return <ul>{sorted.map((i) => <li key={i}>{i}</li>)}</ul>;
}Bad changes the array its parent owns, every time it renders. Caching a component like that would hide or repeat the mutation unpredictably. Good leaves the prop alone, so it can be optimized.
The build-time pipeline
The following diagram shows where the compiler sits in a build.
Because the compiler is a Babel plugin, it fits into any toolchain that can run Babel, including Vite and Next.js. Later chapters cover setup.
What it does not do
Knowing the limits helps you set expectations:
- It does not make every render fast. It avoids repeated work and re-renders of unchanged children. A slow algorithm stays slow on the first render.
- It does not stop a component from re-rendering when its own state changes. It reduces the cost of those renders and the work passed on to children.
- It does not fix code that breaks the Rules of React. It skips that code.
- It does not remove the need to measure. Use the React DevTools Profiler to confirm that there is something worth optimizing and that the compiler helped.
- It works at the level of components and hooks. Plain utility functions outside them are not memoized.
Compiler and manual memoization together
You do not have to delete existing memo, useMemo and useCallback calls to adopt the compiler. The compiler understands them and works with them. For new code, the recommended default is to write plain code and let the compiler handle memoization. Keep a manual useMemo or useCallback when you need precise control, for example when a memoized value is a dependency of useEffect and you want to control exactly when the effect fires. A later chapter covers these decisions in detail.
Common misunderstandings
- "The compiler is a runtime library." The caching logic is generated at build time. At runtime the compiled code only compares inputs and reads from a cache. React 19 supports this directly. React 17 and 18 need a small extra runtime package, as a later chapter explains.
- "Compiled components never re-render." They still render when state changes. The compiler makes a re-render cheaper and prevents unnecessary renders of children.
- "If it compiles, it is correct." The compiler can only check what it can see. It skips code it cannot prove safe, but your own logic is still your responsibility.
- "It replaces understanding re-renders." Knowing why components render is still what lets you find skipped components and fix them.
Exercise
A teammate says: "We turned on the React Compiler, so we can mutate the items prop with items.sort() inside render, because the compiler will memoize it anyway." What is wrong with this, and what should the code do instead?
Show answer
Mutating a prop during render breaks the Rules of React, which the compiler relies on to know that caching is safe. The compiler will skip a component that does this, so it gets no automatic memoization, and the mutation changes the parent's data on every render. Copy the array and sort the copy, for example const sorted = [...items].sort();.
Exercise
Name three differences between writing useMemo and useCallback by hand and relying on the compiler, and say what the compiler does when it cannot prove a component is safe to memoize.
Show answer
The compiler picks what to cache instead of you, derives the dependencies from the code instead of from a hand-written array, and can apply caching in places hooks cannot be used, such as after an early return. Memoization is also inserted at build time. When it cannot prove a component is safe, it leaves that component unchanged, so the component behaves as it did without the compiler.