Sub topic 12
When the Compiler Skips Code and How to Debug It
This chapter assumes you can read a basic Babel or Vite config and know the Rules of React from earlier in this tutorial. It also assumes you have the compiler plugin installed. Here you will learn why the compiler leaves some components uncompiled, how to see that happen, and how to fix it or isolate it.
Skipping is the default failure mode
When the compiler finds code it cannot prove safe to memoize, it does not stop your build. It leaves that component or hook as written and moves on. This is called a bailout. Your app keeps working, but that function gets no automatic memoization.
That is the right default for production, but it hides problems. A component can silently lose its optimization after a harmless-looking edit. Debugging bailouts is mostly about making them visible.
What the compiler looks at
The compiler only considers two kinds of functions:
- Components: functions with a capitalized name that return JSX or other renderable values.
- Hooks: functions whose names start with
use.
Ordinary helper functions, event handlers defined outside components, and utility modules are not compiled on their own. A helper can still be optimized when it is defined inside a component, because it is part of that component's body.
Inside those functions, the compiler analyzes how values flow, and which values can change. A bailout happens when that analysis finds a pattern it must reject.
Common reasons for a bailout
| Cause | Example | Fix |
|---|---|---|
| Mutating props or state during render | `items.sort()` on a prop | Copy first: `[...items].sort()` |
| Mutating a value after passing it to JSX or a hook | `list.push(x)` after `<List data={list} />` | Finish building the value before using it |
| Reading or writing `ref.current` during render | `return <p>{ref.current}</p>` | Read refs in effects or event handlers |
| Writing to outside variables during render | `counter += 1` at module scope | Move the write into an effect or handler |
| Calling hooks conditionally or in loops | `if (ok) useState(0)` | Call hooks at the top level |
| Unsupported syntax | `with` statements, `eval` | Rewrite without them |
Some constructs are only partly supported, and support changes between compiler releases. Check the release notes for your version when a pattern you think is valid gets skipped.
Here is the pair from earlier in the tutorial. The first component mutates its prop, so it is unsafe to memoize. The second renders purely.
// 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 also has a runtime problem. The parent's array changes order every time the child renders. The compiler's refusal is pointing at a real defect.
The debugging loop
The tools from the last two chapters fit together into one loop.
Work through it in this order.
Step 1: Check DevTools
Open React DevTools and look at the component tree. Components the compiler optimized show a "Memo ✨" badge next to their name. A component without the badge was not compiled, or it was compiled by a different build than the one you are running. Make sure you are inspecting a build that includes the plugin. Some setups only apply it in production builds.
Step 2: Run the lint rules
The compiler's lint rules report the same violations the compiler detects. They are the quickest way to get a human-readable reason, and they mark the exact line. They ship in eslint-plugin-react-hooks in recent releases, and earlier as the separate eslint-plugin-react-compiler package. Use whichever matches your installed version.
A rule violation shown in your editor is usually all you need. Fix it, save, and check that the badge returns.
Step 3: Ask the compiler directly
Lint can miss cases, and linting is not the build. When there is no lint error but the badge is still missing, make the compiler report what it does. The Babel plugin accepts two options for this: panicThreshold and logger.
// babel.config.js
module.exports = {
plugins: [
[
'babel-plugin-react-compiler',
{
// 'none' (default): skip silently.
// 'all_errors': fail the build on any bailout.
panicThreshold: 'all_errors',
logger: {
logEvent(filename, event) {
if (event.kind === 'CompileError') {
const line = event.fnLoc ? event.fnLoc.start.line : '?';
console.warn(`[react-compiler] skipped ${filename}:${line}`);
console.warn(event.detail);
}
},
},
},
],
],
};With all_errors, the first bailout throws and stops the build, which is useful in a small reproduction. The logger is better for a real codebase. It prints every skipped function and lets the build finish.
Do not leave panicThreshold: 'all_errors' on in a large legacy codebase. It fails the build on the first violation. Teams do use it in CI for new code, where every component is expected to compile.
Step 4: Check configuration
If nothing was reported for the function, the compiler may never have looked at it. Check these:
compilationModeis'annotation'and the function has no'use memo'directive.- The file is excluded by a
sourcesfilter, if you set one. - The function name does not look like a component or hook.
function list()is not a component.function List()is. - The plugin is not first in the Babel plugin list. Other transforms that rewrite the code first can change what the compiler sees.
- Another bundler loader processes the file before Babel runs, for example with a TypeScript or JSX transform that has already lowered the JSX.
Opting out with a directive
Sometimes the right response to a bailout is not to fix the code now. A component might mutate a third-party model that you cannot change this sprint. If the compiler compiles it and the result behaves differently, you want a fast switch.
Add 'use no memo' as the first statement of the function. The compiler then leaves that function alone.
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 directive is also a diagnostic tool. If an odd bug appears after you enable the compiler, add 'use no memo' to the suspect component. If the bug goes away, the compiled output is involved, and the underlying cause is almost always a Rules of React violation that the compiler's analysis missed or tolerated.
The opposite directive, 'use memo', opts a function in when compilationMode is 'annotation'.
A bailout that hides in plain sight
A component can compile and still not behave the way you expect. The compiler memoizes by comparing inputs. If a parent passes a new object or function through a path the compiler could not analyze, the child's props change on every render and the child re-renders anyway.
Check these:
- The parent is not compiled, so it still creates fresh objects each render. Memoizing the child does not help if its inputs are never stable.
- A value comes from a context or store that updates frequently.
- Props come from a non-compiled library that returns new references each call.
The Memo badge on the child is not enough. Use the React DevTools Profiler, turn on "Record why each component rendered", and read the reason. The reason tells you which prop or state changed.
Recovering after a bailout
Once you have a reason, you usually have three choices:
- Fix the violation. This is the best option, because the code gets safer and the optimization returns.
- Restructure so the offending code lives outside the component, for example in an effect, an event handler, or a custom hook that the compiler can process separately.
- Opt out with
'use no memo'and keep manual memoization in that component until you can do one of the above.
The third option means manual useMemo and useCallback still matter for uncompiled components. Do not strip them from a file that the compiler skips.
Exercise
Your component has no Memo badge in DevTools. ESLint reports nothing. Name three further checks you can make, in order, before editing the component's code.
Show answer
First, confirm you are running a build that includes the plugin, since some setups apply it only in production. Second, turn on the compiler's logger or set panicThreshold to 'all_errors' to get the compiler's own reason for skipping. Third, check configuration: compilationMode 'annotation' without a 'use memo' directive, a sources filter that excludes the file, a function name that does not look like a component or hook, or the plugin not running first in the Babel plugin list.
Exercise
After enabling the compiler, a panel shows stale data. Adding 'use no memo' to the panel's component fixes it. What does this tell you, and what should you do next?
Show answer
It shows the compiled output of that component is involved. The usual cause is a Rules of React violation, such as mutating a value during render or reading a ref during render, that makes memoized results go stale. Keep the directive as a temporary fix with a comment, find the violation (lint rules and the logger can help), fix it, then remove the directive and confirm the Memo badge and correct behavior.