Sub topic 9
Adopting the compiler gradually
This chapter assumes you know function components, props and state, and the useState, useEffect, useMemo and useCallback hooks. You should also have the Babel plugin installed, as covered in the setup chapter. Turning the compiler on for a whole codebase at once is possible, but it is often the wrong first move. Large apps contain code that breaks the Rules of React, and you want to find that code on your schedule, not during a release.
Why roll out in stages
The compiler rewrites components and hooks at build time. If a component relies on behavior the compiler assumes cannot happen, such as mutating a prop during render, the compiled version can behave differently from the original. The compiler skips code it can prove is unsafe, but it cannot catch every violation. A gradual rollout limits the blast radius and lets you check behavior in small steps.
A staged rollout gives you three things:
- Small changes to review and revert.
- Time to fix rule violations that the lint rules reveal.
- A way to compare behavior and performance before and after, one area at a time.
The two levers: modes and directives
You control adoption with one option and two directives.
compilationModeis a plugin option. It decides which functions the compiler considers.'use memo'is a directive that opts a single function in.'use no memo'is a directive that opts a single function out.
A directive is a string literal placed as the first statement of a function body, like 'use strict'.
Compilation modes
| Mode | What gets compiled | Typical use |
|---|---|---|
| `'infer'` (default) | Components and hooks, detected by naming and by whether the function returns JSX or calls hooks | Whole-project adoption |
| `'annotation'` | Only functions marked with `'use memo'` | Cautious first rollout |
| `'all'` | Every top-level function the compiler can handle | Rarely needed. Useful for experiments |
In 'infer' mode, the compiler looks for functions that look like components (capitalized names that return JSX) or hooks (names starting with use that call other hooks). Helper functions that do neither are left alone.
Check the current options against the official documentation for your plugin version, because the list of modes and options has changed between releases.
Step 1: start in annotation mode
Annotation mode compiles nothing until you ask. This lets you install the plugin and ship it with no behavior change, then opt in one function at a time.
// babel.config.js
module.exports = {
plugins: [
[
'babel-plugin-react-compiler',
{
// Compile only functions that opt in with a "use memo" directive.
compilationMode: 'annotation',
// Needed for React 17 or 18; omit for React 19.
target: '18',
},
],
],
};The target option names the React version your output must run on. For React 17 and 18, the compiled code calls a helper from the react-compiler-runtime package, so install that package as a dependency. For React 19, omit target.
Now opt in a function:
function Chart({ data }) {
'use memo';
// Compiled when compilationMode is 'annotation'.
return <canvas data-points={data.length} />;
}Pick a first candidate that meets three conditions:
- It is slow or re-renders often, so you can measure a benefit.
- It has few dependencies on shared mutable objects.
- It has good test coverage or is easy to check by hand.
Leaf components that render lists or charts are usually good starting points. Components that read from global mutable stores or third-party objects are poor first choices.
Step 2: widen the scope
After a few annotated functions behave well, you have two ways to expand.
- Annotate more functions, directory by directory.
- Restrict the Babel plugin to certain paths, so
'infer'mode applies only to parts of the repository.
Babel's overrides field can apply the plugin to some files only. This is a standard Babel feature, not a compiler option.
// babel.config.js
module.exports = {
overrides: [
{
// Compile only the dashboard feature for now.
test: './src/features/dashboard/**/*.{js,jsx}',
plugins: [['babel-plugin-react-compiler', {}]],
},
],
};Here the default 'infer' mode runs, but only inside the dashboard directory. When that area is stable, add the next directory to test or switch to a project-wide plugin entry.
With Vite, you pass the same plugin through @vitejs/plugin-react. Path-based scoping there is easier to do with Babel's overrides or with a custom filter, depending on your setup.
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
babel: {
plugins: [
['babel-plugin-react-compiler', { compilationMode: 'annotation' }],
],
},
}),
],
});Step 3: switch to infer mode and opt out exceptions
Once most of the codebase compiles cleanly, move to the default mode and use 'use no memo' for the few functions that still cause trouble.
function LegacyWidget({ model }) {
'use no memo';
// Skipped by the compiler, for example while a rule violation is being fixed.
model.count += 1;
return <span>{model.count}</span>;
}The opt-out is a temporary tool. It marks a known problem so the rest of the project can proceed. Leave a comment next to each one that says why it is there and what must change before it can be removed. A search for 'use no memo' then gives you a list of remaining work.
The directive works in every mode. In 'annotation' mode it is redundant, since unannotated functions are skipped anyway. In 'infer' mode it is how you exclude a function.
A rollout path in one picture
Fixing what the rollout reveals
Gradual adoption surfaces violations of the Rules of React. The most common one is mutating a value during render.
// 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>;
}Array.prototype.sort changes the array in place. Because items belongs to the parent, the child is changing data it does not own, and a memoized result could go stale or the parent could see surprising changes. Copying first keeps rendering pure.
Other typical findings:
- Writing to a variable declared outside the component during render.
- Reading or writing
ref.currentduring render, rather than in an event handler or effect. - Changing state objects directly instead of creating a new object.
- Calling hooks conditionally.
Fix these in the source. Silencing the lint rule hides the problem, and the compiler may then skip the function or, worse, compile it in a way that changes behavior.
Checking each stage
After every widening step, verify before moving on:
- Run your tests and the ESLint rules for the compiler.
- Open React DevTools and look for the "Memo" badge next to the components you expect to be compiled. Components the compiler optimized show this badge.
- Profile a representative interaction before and after, using the React DevTools Profiler, and compare render counts and times.
- Check in a staging build that behavior is unchanged for flows that depend on timing, such as focus handling and animations.
If a component you annotated has no badge, the compiler skipped it. The next chapters cover the diagnostics for that. For now, treat a missing badge as a signal to read the compiler's output or lint messages before widening further.
Mixing compiled and manual memoization
During the rollout you will have components that still use useMemo, useCallback and memo. Leave them in place. The compiler understands existing manual memoization and preserves its meaning. Removing it early adds risk without a clear benefit, especially where useMemo or useCallback values appear in effect dependency arrays, because the compiler may memoize differently and change when the effect runs.
Compare the manual version with the version the compiler can handle by itself:
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>
</>
);
}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>
</>
);
}Remove manual memoization in new code first. In existing code, remove it only after the component is compiled, tested and profiled, and keep it where it controls effect timing.
Common mistakes
- Rolling out everywhere on day one. You get many findings at once and cannot tell which change caused a regression.
- Annotating without a mode change. In
'infer'mode,'use memo'adds nothing for functions that already look like components. It matters in'annotation'mode. - Leaving
'use no memo'permanently. Opt-outs pile up and the project never reaches full coverage. - Forgetting the runtime for React 17 and 18. Without
react-compiler-runtimeand the righttarget, the build or the app fails when the compiled code runs. - Treating the compiler as a fix for slow code. It reduces repeated work. It does not fix an expensive algorithm or an oversized list.
Exercise
Your team has a large React 18 app and wants to try the compiler without changing behavior in production on day one. Which compilation mode and options do you configure, how do you opt in the first component, and what must you install besides the Babel plugin?
Show answer
Set compilationMode: 'annotation' and target: '18' in the babel-plugin-react-compiler options. Install react-compiler-runtime as well, because React 18 needs it for the compiled output. Opt in the first component by adding 'use memo'; as the first statement in its function body. Nothing else is compiled until you annotate it.
Exercise
After switching to the default mode, a component LegacyWidget increments model.count during render and breaks once compiled. What is the short-term fix and what is the real fix?
Show answer
Short term, add 'use no memo'; at the top of the function body so the compiler skips it, with a comment explaining why. The real fix is to stop mutating model during render, for example by keeping the count in state or deriving it from props, so the component follows the Rules of React and the directive can be removed.