Sub topic 10
Finding problems with the lint rules
This chapter assumes you know the Rules of React from earlier in this tutorial: components must be pure during render, and props and state are immutable. It also assumes you can edit an ESLint configuration. The chapter covers what the compiler's lint rules report, how to install them, how to read their diagnostics, and how to fix or suppress what they find.
Why a separate lint step exists
The React Compiler does not fail your build when it meets code it cannot optimize. It skips that component or hook and moves on. The skipped code still runs correctly, but it gets no automatic memoization, and nothing in the browser tells you so.
The lint rules close that gap. They run the compiler's analysis inside your editor and CI and report each place where the compiler would bail out, usually with the reason. You can fix problems while you write the code, before you profile anything.
Some properties to keep in mind:
- The lint rules do not need the Babel plugin installed in your build. You can run them on a codebase you have not yet compiled to find out how ready it is.
- A lint error is not a runtime error. The code works today. The error says the compiler cannot prove the code follows the Rules of React.
- Many findings are real bugs: stale UI, mutated props, or state updates during render. Fixing them helps even without the compiler.
Installing the rules
There are two packages, depending on your version of the tooling.
The standalone package is eslint-plugin-react-compiler. It exposes a single rule, react-compiler/react-compiler. Newer releases of eslint-plugin-react-hooks fold the compiler's checks into that plugin as several smaller rules, such as purity, immutability and refs checks, and the standalone package is being phased out. Check which version your project uses. Rule names and preset names differ between versions, so confirm them against the plugin's README before copying a configuration.
Install the standalone package:
npm install --save-dev eslint-plugin-react-compilerThen enable it in an ESLint flat configuration:
// eslint.config.js
import reactCompiler from 'eslint-plugin-react-compiler';
export default [
{
plugins: {
'react-compiler': reactCompiler,
},
rules: {
'react-compiler/react-compiler': 'error',
},
},
];If your project still uses the legacy .eslintrc format, list the plugin by name instead:
// .eslintrc.js
module.exports = {
plugins: ['eslint-plugin-react-compiler'],
rules: {
'react-compiler/react-compiler': 'error',
},
};Use 'warn' instead of 'error' while you triage an existing codebase, so a flood of findings does not block every pull request.
How the rule decides what to report
The rule parses each function that looks like a component (a capitalized name that returns JSX) or a hook (a name starting with use). It builds the same internal representation the compiler uses and tracks every value through render. It reports a diagnostic when it finds something the compiler cannot safely memoize.
flowchart TD
A[Source file] --> B[Find components and hooks]
B --> C[Analyze data flow in render]
C --> D{Follows the Rules of React?}
D -- Yes --> E[No diagnostic. Compiler can memoize]
D -- No --> F[Lint diagnostic with reason and location]
F --> G{Can you fix the code?}
G -- Yes --> H[Fix the violation]
G -- No --> I[Add use no memo and a comment]
H --> J[Re-run lint]
I --> JTreat the rule as conservative. Code it flags might be safe in practice, and code that passes might still contain a bug the analysis cannot see. It checks a defined set of patterns, not the full behavior of your program.
Common diagnostics and their fixes
Most findings fall into a few groups. The exact message text changes between versions, so match on the cause, not the wording.
| Cause | What the rule objects to | Typical fix |
|---|---|---|
| Mutating props or state | Calling `sort`, `push` or assigning to a property of a value you do not own | Copy first, then change the copy |
| Writing to a ref during render | Assigning `ref.current` in the render body | Move the write into an event handler or effect, or use state |
| Setting state during render | Calling a setter unconditionally in the render body | Derive the value instead, or move the update to an event or effect |
| Mutating a value after it is used | Changing an object after passing it to JSX or a hook | Finish building the value before using it |
| Conditional hooks | Calling a hook inside `if`, a loop, or after an early return | Call every hook at the top level |
| Unsupported syntax | Constructs the compiler does not handle yet | Rewrite, or opt the function out |
Mutating props
This is the example from the spine. Sorting items in place changes an array the parent owns, so the compiler cannot know whether the parent's value is still valid.
// 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>;
}The mutation is also a real bug without the compiler. Every render sorts the parent's array again, and any other component reading that array sees it change.
Writing to a ref during render
A ref is a mutable box that React does not track. Writing to it while rendering means the output can differ between two renders with identical inputs.
import { useRef } from 'react';
// Flagged: writes ref.current in the render body.
function RenderCounter() {
const renders = useRef(0);
renders.current += 1;
return <p>Renders: {renders.current}</p>;
}If the number is meant to appear on screen, it is state, not a ref:
import { useState } from 'react';
function ClickCounter() {
const [clicks, setClicks] = useState(0);
return (
<button onClick={() => setClicks((n) => n + 1)}>
Clicked {clicks} times
</button>
);
}Refs are fine in event handlers and effects. The rule objects only to reading or writing current while the component renders. A common legitimate exception, lazy initialization behind a null check, may still be flagged. Prefer useState(() => initialValue) for that case.
Setting state during render
import { useState } from 'react';
// Flagged: calls the setter on every render.
function Greeting({ name }) {
const [label, setLabel] = useState('');
setLabel(`Hello, ${name}`);
return <h1>{label}</h1>;
}
// Fixed: compute the value, no state needed.
function GreetingFixed({ name }) {
const label = `Hello, ${name}`;
return <h1>{label}</h1>;
}Anything you can compute from props and state during render should not be stored in state at all.
Reading a diagnostic
Each report has three useful parts: the location, the category, and the reason. Work through them in this order:
- Open the reported line. It usually points at the mutation or the unsafe read, not at the component's name.
- Identify who owns the value. A prop, a state value, a context value and a hook's return value are all immutable to you. A variable you created inside this render is yours to change until you pass it to JSX or a hook.
- Pick the smallest change that keeps behavior the same. Copying is usually enough.
After a fix, save the file and wait for the editor to clear the squiggle. If it does not clear, the rule may be reporting a second problem on the same function, since one violation can hide another.
ESLint suppressions change compiler behavior
By default the compiler also looks for ESLint suppression comments aimed at the Rules of Hooks and exhaustive dependencies. If a component contains one, the compiler skips that component, because a suppressed rule means the code might break the assumptions the compiler needs.
import { useEffect } from 'react';
function Tracker({ id, onSeen }) {
useEffect(() => {
onSeen(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <span>{id}</span>;
}This component will not be compiled. Before reaching for a disable comment, fix the dependency array. A missing dependency is a stale-closure bug whether or not the compiler is involved.
When you cannot fix it right now
Sometimes a finding comes from code you do not own, or from a pattern that needs a larger refactor. Opt that one function out with the use no memo directive and leave a note explaining why:
function LegacyWidget({ model }) {
'use no memo';
// TODO: model is mutated by a third-party store. Remove once it is immutable.
model.count += 1;
return <span>{model.count}</span>;
}The directive tells the compiler to skip this function, and the lint rule stops reporting it. That is the intended use, but it hides a real violation. Search for use no memo periodically so the opt-outs do not become permanent.
Handling false positives
If you are sure a diagnostic is wrong, you have two options, and you should pick them in this order:
- Restructure the code so the intent is clear to the analysis. A small helper function or a local copy often removes the report.
- Use
use no memoon the function and file an issue with a minimal example.
Avoid turning the rule off across the whole project to silence one report. You would lose the feedback on every other component.
A workflow for an existing codebase
- Enable the rule as
warnand run ESLint on the whole project. - Group the findings by cause using the table above. Mutation of props and writes to refs account for most of them.
- Fix whole categories at a time, starting with the ones that are also real bugs.
- Switch the rule to
erroronce the count reaches zero, so new violations cannot merge. - Confirm that the fixed components are actually compiled, as described in the next chapter on React DevTools.
Exercise
A teammate's component calls items.reverse() on a prop array and the compiler lint rule reports it. They suggest adding use no memo so the warning goes away. What do you recommend, and why?
Show answer
Fix the code instead of opting out. reverse() mutates the array in place, so it changes a value the parent owns and can produce wrong output elsewhere. Write const reversed = [...items].reverse(); and render reversed. Use use no memo only when the violation cannot be fixed now, and then add a comment explaining why.
Exercise
Why can a component with an eslint-disable-next-line react-hooks/exhaustive-deps comment be missing from the compiled output, even though the lint rule reports nothing?
Show answer
By default the compiler skips components that suppress the hook lint rules, because the suppression signals that the code may break the assumptions memoization relies on. Remove the suppression by fixing the dependency array, and the component becomes eligible for compilation.