Sub topic 13
The React Compiler and the future of manual memoization
This chapter assumes you have read the earlier chapters. You should know why components re-render, how React.memo, useMemo and useCallback compare values with Object.is, and why inline objects and functions break memoization. It covers what the React Compiler does, how to adopt it, and what happens to your existing manual memoization afterwards.
What the compiler is
The React Compiler is a build-time tool. It is a Babel plugin, babel-plugin-react-compiler, that reads your components and custom hooks and rewrites them so that values are cached automatically. You write plain code, and the output behaves as if you had placed useMemo, useCallback and memo where they help.
The compiler does not change React's render model. A component still re-renders when its state changes or its parent re-renders. What changes is the work inside a render. The compiler wraps each piece of computed output in a cache check, and React skips unchanged pieces, including child elements. The result is that a child element is only recreated when the values it depends on have changed.
Here is a component written with no manual memoization:
import { useState } from 'react';
export function ProductList({ products }) {
const [query, setQuery] = useState('');
const [darkMode, setDarkMode] = useState(false);
const visible = products.filter((p) =>
p.name.toLowerCase().includes(query.toLowerCase())
);
return (
<div className={darkMode ? 'dark' : 'light'}>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<button onClick={() => setDarkMode((d) => !d)}>Toggle theme</button>
<ul>
{visible.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
</div>
);
}Without the compiler, toggling the theme runs filter again. With the compiler, visible is cached against products and query, so the toggle reuses it. This is the same behavior you wrote by hand with useMemo in the ProductList example from the useMemo chapter.
How it decides what to cache
The compiler analyzes each component and hook as a data-flow graph. It works out which values depend on which inputs (props, state, context). Then it groups the computations into blocks, and each block gets a cache slot keyed by its inputs. When the inputs are the same according to Object.is, the cached result is returned. The cache is stored per component instance through an internal hook.
Two properties matter in practice:
- Granularity is finer than you would write by hand. The compiler can cache one JSX element in a tree while recomputing its sibling.
- It can memoize code that hooks cannot reach. Hooks cannot be called after an early
returnor inside a condition, so a manualuseMemoplaced there is a rule violation. The compiler has no such restriction on the values it caches.
export function Greeting({ user, theme }) {
if (user == null) {
return <p>Please sign in.</p>;
}
// Cannot be wrapped in useMemo by hand: it comes after an early return.
// The compiler can still cache this element against `user` and `theme`.
const card = <section className={theme}>{user.name}</section>;
return card;
}The following diagram shows where the compiler sits in the pipeline.
Enabling the compiler
The compiler is a plugin for your build tool. Install it as a dev dependency:
npm install --save-dev --save-exact babel-plugin-react-compiler@latestWith Vite and @vitejs/plugin-react, you pass it through the Babel options. Keep it first in the plugin list, because it needs to see the original source before other transforms change it.
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
babel: {
plugins: ['babel-plugin-react-compiler'],
},
}),
],
});React 19 includes the runtime support the compiled output needs. React 17 and 18 can also use the compiler, but you must install react-compiler-runtime and set the plugin's target option to match your React version. Check the current React documentation for the exact option values before you configure an older version.
Adopting it gradually
You do not have to compile everything at once. The compilationMode option controls which functions the compiler touches.
// vite.config.js (incremental adoption)
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
babel: {
plugins: [
['babel-plugin-react-compiler', { compilationMode: 'annotation' }],
],
},
}),
],
});In annotation mode, only functions that opt in are compiled. You opt in with a directive at the top of the function body:
export function ProductList({ products }) {
'use memo';
// ... compiled because of the directive
return null;
}The opposite directive, 'use no memo', excludes a function when the default mode is on. It is a temporary escape hatch for a component that misbehaves after compilation, not a permanent setting.
The Rules of React still apply
The compiler is only safe if your code follows the Rules of React. The main ones are:
- Components and hooks must be pure during render. The same props, state and context must produce the same output.
- Props, state and values returned from hooks must not be mutated.
- Hooks are called only at the top level of components and other hooks.
- Refs are not read or written during render, except for lazy initialization.
When the compiler detects code it cannot prove safe, it skips that component and leaves it as written. The app still works, but you lose the optimization for it. The code below breaks purity, so the compiler will not optimize it safely.
let renderCount = 0;
export function Counter({ items }) {
// Mutating a module-level value during render is a side effect.
renderCount += 1;
// Mutating a prop breaks the rule that props are read-only.
items.sort();
return <p>Rendered {renderCount} times with {items.length} items</p>;
}The eslint-plugin-react-hooks package includes rules that report these problems, and they run without the compiler installed. Enable them before you turn the compiler on. They show you which components will be skipped.
What happens to existing useMemo, useCallback and memo
You do not need to delete manual memoization when you adopt the compiler. Existing calls keep working, and the compiler treats them as part of the code it analyzes. React's guidance for existing code is to leave it alone unless you have a reason to remove it, because removing a hook can change the compiled output in ways that are hard to predict.
For new code, rely on the compiler first and add manual memoization only where it does something the compiler cannot. There are three such cases:
- Effect dependencies you need to control. If an object or function is in an effect's dependency array, and you need it to change only when specific inputs change, a
useMemooruseCallbackstates that intent explicitly. The compiler may also keep the value stable, but a manual hook makes the guarantee part of your code instead of a side effect of compilation. - Components the compiler skips. If a component breaks a rule, or you excluded it with
'use no memo', the old tools apply as before. - Code outside components and hooks. The compiler only transforms components and hooks. A plain utility function that is expensive is not cached by the compiler, although a component that calls it will have its result cached against the inputs.
Here is a case where an explicit hook still states intent:
import { useEffect, useMemo } from 'react';
export function Subscription({ channel, token }) {
const options = useMemo(() => ({ channel, token }), [channel, token]);
useEffect(() => {
const connection = connect(options);
return () => connection.close();
}, [options]);
return null;
}
function connect(options) {
console.log('connect', options.channel);
return { close() {} };
}If you removed the useMemo and relied on the compiler, the effect would probably still behave the same. The explicit version does not depend on that.
Verifying the compiler is working
You can confirm compilation in React DevTools. Components the compiler optimized show a "Memo ✨" badge next to their name. In the Profiler, a compiled component whose inputs did not change is skipped, and it appears as not rendered for that commit.
The general rule from the Profiler chapter applies here as well: measure before and after. The compiler does not make a slow algorithm fast. It removes repeated work caused by re-renders. If your slowdown comes from an expensive calculation that runs on every legitimate change, or from rendering ten thousand rows, the compiler will not fix that. Virtualization, pagination and better data structures still apply.
What the compiler does not replace
| Problem | Does the compiler help? | Better tool |
|---|---|---|
| Child re-renders when the parent's unrelated state changes | Yes, usually | Compiler, or moving state down |
| Expensive filter re-runs on every render | Yes, it caches against inputs | Compiler, or `useMemo` |
| Unstable function or object in an effect dependency array | Often, but not guaranteed | `useMemo` or `useCallback` |
| Context value changes and many consumers re-render | Partly | Split contexts, select narrower values |
| Rendering thousands of DOM nodes | No | Virtualization |
| Component breaks the Rules of React | No, it is skipped | Fix the code |
| Code in a plain function outside components and hooks | No | Manual caching |
Common mistakes
- Treating the compiler as a fix for impure code. If a component mutates props or reads refs during render, it will be skipped or, worse, behave incorrectly. Fix the code first.
- Deleting all
useMemoanduseCallbackcalls on adoption. This can change behavior for effects. Remove them one at a time, and only with a measured reason. - Skipping the lint rules. The ESLint rules tell you ahead of time which components the compiler will refuse.
- Assuming a faster app without measuring. Compare Profiler recordings with the compiler on and off for a real interaction.
- Expecting it to work in files that are not transformed. Only code passed through the Babel plugin is compiled. A library you import from
node_modulesis not compiled unless its authors shipped it that way.
Summary of the decision
The compiler changes the default. Before, you wrote plain code and added memoization after a Profiler measurement showed a problem. Now you write plain code, let the build step memoize it, and use manual hooks for explicit guarantees such as effect dependencies. The earlier chapters remain useful: referential equality, dependency arrays and state placement explain what the compiler is doing, and they let you debug a component when it does not behave as expected.
Exercise
A team enables the React Compiler in annotation mode. A component named Report is not annotated. Does the compiler optimize it, and what is the smallest change that opts it in?
Show answer
No, in annotation mode only functions that opt in are compiled, so Report is left as written. Adding the directive 'use memo' as the first statement of the function body opts it in.
Exercise
A component sorts its items prop in place with items.sort() during render. What happens when the compiler processes it, and how do you fix it?
Show answer
The compiler cannot prove the component is safe because it mutates a prop, so it skips the component and leaves it unoptimized (the lint rules also report it). Fix it by sorting a copy, for example [...items].sort(), so render stays pure.
Exercise
You adopt the compiler in an existing codebase. A teammate wants to delete every useMemo and useCallback in one commit. Give one reason to avoid that, and name one case where you would still write a manual hook in new code.
Show answer
Removing hooks can change which values stay stable, which can alter how effects with those values in their dependency arrays behave, and it is hard to predict, so remove them one at a time with a measurement. In new code, you would still write useMemo or useCallback for a value in an effect dependency array when you want its stability to be an explicit guarantee.