Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 132 ยท Performance

The React Compiler

What the React Compiler does, how it decides what to cache, the Rules of React it relies on, how to opt in or out, and a runnable model of its compiled output - no more manual memo.

In the previous lessons you saw that making React fast often means adding memo, useMemo and useCallback in the right places, and keeping every prop stable. It works, but it is tedious, it clutters the code, and one forgotten dependency quietly undoes it all. The React Compiler takes that job away from you. It is a build-time tool that reads your components, works out which values depend on which inputs, and inserts caching for you.

This lesson explains what it does, what it assumes about your code (the "Rules of React"), how to adopt it gradually and how to opt a component out. The compiler is a build step that our in-browser editor does not have, so the real tool appears in read-only snippets. To make the idea concrete anyway, we build a small hand-written model of what compiled code does and run it. Background: memo and useMemo and useCallback.

What the compiler does

Think of useMemo and useCallback as you telling React "remember this unless these inputs change". The compiler does the same analysis automatically:

  • It parses each component and custom hook into a data-flow graph: which variables are computed from which props, state and other variables.
  • It splits the component's output into pieces ("reactive scopes"), each of which depends on a certain set of inputs.
  • For each scope it generates a check: "if none of my inputs changed since the last render, reuse the previous result; otherwise recompute and store it".

The effect is similar to wrapping every expensive value, every JSX element and every handler in memoization, at a much finer grain than anyone writes by hand, and it even works in places hooks cannot go, such as after an early return.

A model of compiled output

Real compiler output is low-level, but the idea fits in a few lines. The component gets a cache, an array of slots that React keeps for that component instance. Each slot holds an input or an output from the last render.

This runnable model uses a tiny useCache hook that we wrote for the lesson (the real compiler uses a React-provided cache). The Counter component below is written the "compiled" way by hand: it recomputes the label only when count changed, and reuses the previously created <Footer /> element, whose identity is what lets React skip rendering it.

A hand-written model of compiled output

On mount the console shows recomputing label, Counter rendered and Footer rendered (the footer element is created for the first time). Press "Add to other": only Counter rendered appears. The label's input (count) is unchanged, so its slot is reused, and the cached <Footer /> element is the very same object as last time, so React skips Footer without any memo. Press "Add to count": now recomputing label appears again, followed by Counter rendered, and Footer still stays silent.

That is the heart of the compiler: compare inputs, reuse the previous output, recompute only what depends on what changed. Every compiled component looks like many small versions of the if ($[0] !== count) block, with the slots managed for you. You write the plain version, and the compiler produces the cached one.

JSX
// Read-only: the shape of real output (simplified; names and details vary by version)
import { c as _c } from 'react/compiler-runtime';

function Counter({ items }) {
  const $ = _c(3);
  let visible;
  if ($[0] !== items) {
    visible = items.filter((item) => item.inStock);
    $[0] = items;
    $[1] = visible;
  } else {
    visible = $[1];
  }
  // ...JSX is cached the same way
}

The Rules of React

The compiler can only reuse a result safely if running the component again with the same inputs would give the same output. That is exactly what the Rules of React demand, and they are the same rules that make code correct in general:

  1. Components and hooks are pure. The same props, state and context give the same JSX. No random numbers, no reading the clock, no writing to variables that live outside the component while rendering. See Keeping Components Pure.
  2. Never mutate props, state or values returned from hooks. Create copies instead. See Objects and Arrays in State.
  3. React calls components and hooks, you do not. Do not call a component as a function, and do not pass hooks around as values.
  4. Follow the Rules of Hooks: call them at the top level, in the same order every time. See The Rules of Hooks.
  5. Side effects belong in event handlers and effects, not in the render body.

When code breaks these rules, the optimization is unsafe. The compiler is conservative: if it cannot prove a component follows the rules, it skips that component (and can report why) instead of generating wrong code. Your app keeps working; that one component just is not optimized.

What breaking the rules looks like

An impure render is a bug even without the compiler, and StrictMode in development exposes it by rendering twice. Here a module-level counter is changed during render:

An impure component (breaks the rules)

Each Receipt is rendered twice by StrictMode, so the numbers climb by two per component: the console lists render of Tea sees renderNumber = 1 and = 2, then the same for Cake with = 3 and = 4. The page itself shows Tea: receipt #2 and Cake: receipt #4, the numbers from the last of the two renders. With a pure component the two renders would be identical. If a compiler cached the result of Receipt, the counter would stop changing altogether, so the program would behave differently after compilation. That is the kind of difference the Rules exist to prevent.

The second classic violation is mutating something you were given:

Mutating a prop during render (breaks the rules)

The first paragraph is rendered before SortedList runs, so it shows Zoe, Ada, Kim. After the mutation, the parent's own array is Ada, Kim, Zoe, and any later render of the parent (or any other component sharing that array) sees the changed order. Because names is the same array object, memo and the compiler's input checks also cannot detect that its contents changed. The fix is the line in SafeSortedList: copy first.

The compiler assumes your inputs are never mutated. If you mutate props or state in place, a cached result will be reused with stale data, and the bug is hard to see. This is why the rules matter more, not less, with the compiler enabled.

Adopting the compiler (read-only)

The compiler ships as a Babel plugin named babel-plugin-react-compiler. It reached a stable 1.0 release in late 2025, and frameworks and starter templates offer a switch to turn it on. The exact option names change between tools and versions, so use these snippets as a sketch and check the current documentation.

Terminal
npm install -D babel-plugin-react-compiler
JavaScript
// vite.config.js (sketch): add the plugin to the React Babel step
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: [['babel-plugin-react-compiler', {}]],
      },
    }),
  ],
});
JavaScript
// next.config.js (sketch): frameworks expose a flag
module.exports = {
  reactCompiler: true,
};

The compiler works with React 19 out of the box. For React 17 and 18 it needs a small runtime package and a target setting, so check the docs for your version.

Rolling it out gradually

Turning it on for a large existing app all at once is the risky approach. Better options:

  • Annotation mode: compile only the components that opt in with a "use memo" directive. Start with one slow screen and grow from there.
  • Directory or file rules in your build config, to compile one feature folder first.
  • Run the tests and the linter first. If your suite is green and the lint rules below are clean, the compiler is unlikely to surprise you.

Opting out: "use no memo"

If one component misbehaves under the compiler, you can exclude it with a directive as the first statement of the function, while you fix the underlying rule violation:

JSX
function LegacyWidget({ data }) {
  'use no memo';
  // legacy code that mutates things; compiled output is skipped for this function
  return <div>{data.label}</div>;
}

The directive is a temporary escape hatch with a comment explaining why, not a place to leave problems forever.

Lint rules

eslint-plugin-react-hooks includes rules that report code the compiler cannot optimize or that breaks the Rules of React: mutation of props and state, reading refs during render, conditional hooks, impure calls in render. Enable it even if you never turn the compiler on: it finds real bugs. See Setting Up a React Project.

Compiler or manual memoization?

Situation Recommendation
New project with the compiler on Write plain code. Skip useMemo, useCallback and memo unless you measure a need.
Existing code with hand-written memoization Leave it. The compiler works alongside it. Remove it only when tests and profiling show nothing changes.
A value used as an effect dependency that must keep its identity Keep useMemo/useCallback there: you want an explicit guarantee.
No compiler (older toolchain, unsupported setup) Use the techniques from memo: colocate state, pass children, memoize measured hot spots.
Slow because of 10,000 rows Neither: use virtualization.

What the compiler does not fix

  • Expensive work that really changes every time: it can skip repeats, but not make one calculation cheap.
  • Too much data in the DOM, slow network, huge bundles. See Large Lists and Code Splitting.
  • Bad architecture: state kept too high still renders a lot of components whenever it changes; the compiler lessens the damage but state colocation is still better.
  • Effects that run too often: that is a dependency design problem, see Effect Dependencies.

Verify with the profiler

Compiled components show a badge in React DevTools ("Memo" with a sparkle icon in current versions), and you can compare render counts before and after. Trust measurements rather than guesses. The next lesson, Profiling and Debugging Performance, shows how to count renders yourself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the React Compiler do?

    It analyzes data flow in components and hooks and generates code that caches results whose inputs have not changed, similar to automatic useMemo/useCallback/memo.
  2. 2. A component writes to a variable outside itself while rendering. What does the compiler do with it?

    The compiler is conservative. If it cannot guarantee safety it leaves the component as it is, so the app keeps working but that component is not memoized.
  3. 3. Why is items.sort() inside a component a problem?

    sort works in place. Mutating props or state means the same object has different contents, which breaks memoization. Copy first: [...items].sort().
  4. 4. How do you exclude a single component from compilation?

    The 'use no memo' directive opts a function out of compiler optimization, which is a temporary escape hatch while you fix rule violations.
  5. 5. In a project with the compiler enabled, what is the recommended default for new code?

    The compiler handles memoization automatically. Manual hooks remain available for precise control, such as stable effect dependencies.

Summary

  • The React Compiler is a build-time tool that adds fine-grained memoization automatically: it compares inputs and reuses previous output for each part of a component.
  • It relies on the Rules of React: pure render, no mutation of props or state, hooks at the top level, side effects outside render.
  • When it cannot prove a component follows the rules, it skips that component; lint rules from eslint-plugin-react-hooks point out the problems.
  • Adopt it gradually (annotation mode, one folder at a time) and opt out single components with "use no memo" as a temporary measure.
  • With the compiler you rarely write memo, useMemo or useCallback; understanding why components re-render is still essential.
  • It does not replace virtualization, code splitting, less data or better state placement.

Next: Profiling and Debugging Performance