ReactAdvanced

React Compiler: Automatic Memoisation Explained

Discover the React Compiler: how automatic build-time memoisation works, configuring it in Vite, debugging optimizations, and when to opt out.

React CourseLesson 50 of 66 (76% complete)
All React lessons (66)View curriculum

What you will learn

In the previous lesson, you saw how much mental effort is required to maintain manual memoisation:

  • Wrapping functions in useCallback.
  • Wrapping objects in useMemo.
  • Wrapping components in React.memo.
  • Auditing dependency arrays to prevent stale closures.

For years, React developers asked: “Why can’t the framework just do this for us?”

With the release of the React Compiler (stable 1.0), React now does exactly that.

In this lesson, you will learn:

  • What the React Compiler is and how it differs from traditional runtime hooks.
  • How the compiler analyzes JavaScript at build time to auto-memoise values, JSX, and components.
  • How to add the React Compiler to a modern Vite React project.
  • How to verify compiler optimizations in React DevTools.
  • How to opt out specific files or components when needed using directives.

What is the React Compiler?

The React Compiler is an opt-in, build-time Babel plugin created by the React core team.

Instead of requiring developers to manually write useMemo and useCallback, the compiler parses your code at build time, models JavaScript semantics, and injects fine-grained memoisation automatically.

Traditional React (Developer burden):
Developer writes:   useMemo, useCallback, React.memo, dependency arrays
Runtime cost:       Developer time, bugs, stale closures

With React Compiler (Automated):
Developer writes:   Standard, idiomatic, clean JavaScript
Compiler output:    Optimized code with fine-grained memoisation baked in

What You Write vs What the Compiler Produces

Consider this simple component:

// What YOU write (clean and straightforward)
function FriendList({ friends, filterText }) {
  const visibleFriends = friends.filter(f => f.name.includes(filterText));

  return (
    <ul>
      {visibleFriends.map(f => (
        <FriendCard key={f.id} friend={f} />
      ))}
    </ul>
  );
}

Under the hood, the compiler transforms your code into a structure that caches visibleFriends and the rendered JSX elements, automatically updating only when friends or filterText actually changes.

You get the performance benefits of useMemo and React.memo everywhere without typing a single dependency array!

The Rules of React: The Foundation of the Compiler

The React Compiler can only optimize code that obeys the fundamental Rules of React:

  1. Components must be pure functions: Given the same inputs (props, state, context), a component must always return the same JSX.
  2. Never mutate existing state or props: Do not write props.user.age = 25 or state.items.push(newItem).
  3. Never call hooks conditionally: Always call hooks at the top level.
  4. Side effects belong in Effects or Actions: Never perform network requests or mutate globals during the render pass.

If your code already obeys these rules, the compiler can optimize it safely without breaking behavior.

How to Set Up the React Compiler in Vite

Adding the compiler to a standard Vite React project takes just a few steps:

1. Install the compiler package

npm install -D babel-plugin-react-compiler

2. Configure vite.config.js

Open your vite.config.js file and pass the Babel plugin to @vitejs/plugin-react:

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: [
          ['babel-plugin-react-compiler', {}]
        ],
      },
    }),
  ],
});

That’s it! When you run npm run dev or npm run build, the compiler automatically analyzes and optimizes your components.

Verifying in React DevTools

How do you know if the compiler is actually optimizing your components?

  1. Open your app in Chrome with React Developer Tools installed.
  2. Open the Components tab.
  3. Next to compiled components, you will see a small Memo badge!

Hovering over the badge confirms:

“Memoized by React Compiler”

If a component does not show the badge, it means the compiler detected a pattern that violated the Rules of React and safely skipped optimizing that specific component while keeping the rest of your app working normally.

Opting Out: The “use no memo” Directive

What if you have a legacy component or a third-party pattern that does not work well with the compiler?

You do not have to turn off the compiler for your whole project. You can opt out an individual component or file using the "use no memo" directive:

// Opting out a specific component
function ComplexLegacyChart({ data }) {
  "use no memo";

  // The compiler will skip this component and leave it untouched
  return <canvas id="legacy-chart" />;
}

This progressive adoption model allows you to adopt the compiler in large codebases safely.

Should You Delete Existing useMemo and useCallback?

If you enable the React Compiler in an existing codebase:

  • Do NOT spend days manually deleting existing useMemo and useCallback calls.
  • The compiler understands existing hooks and compiles them cleanly.
  • For new code, simply write clean JavaScript without useMemo or useCallback.
  • Remove manual hooks gradually when refactoring or updating features.

Common mistakes

1. Mutating props or state

// Incorrect: Violates the Rules of React; compiler will bail out
function CartList({ items }) {
  // Mutating an existing array!
  items.sort((a, b) => a.price - b.price);
  return <div>...</div>;
}

// Correct: Create a copy before sorting
function CartList({ items }) {
  const sorted = [...items].sort((a, b) => a.price - b.price);
  return <div>...</div>;
}

2. Expecting the compiler to fix slow network requests

The compiler optimizes React component re-renders. It does not make slow backend APIs, massive image downloads, or blocking synchronous algorithms faster.

3. Assuming the compiler replaces State or Effects

The compiler only automates memoisation. You still use useState for state, useActionState for forms, and useEffect for outside synchronization.

Practice

  1. Run the official React Compiler healthcheck in a terminal: npx react-compiler-healthcheck. Review the compatibility score.
  2. Configure babel-plugin-react-compiler in a demo Vite project.
  3. Open React DevTools Components tab and locate the Memo badge on your components.
  4. Add a deliberate mutation (e.g. props.data.count++) inside a component and observe how the compiler skips that component.
  5. Add the "use no memo" directive to a component and verify in React DevTools that the memo badge disappears.
  6. Compare a component written with manual useMemo + useCallback against the clean version compiled automatically. Note the improvement in code readability.

Recap

  • The React Compiler is a build-time tool that automates component and value memoisation.
  • It eliminates the need to manually write useMemo, useCallback, and React.memo in new code.
  • The compiler requires your code to follow the Rules of React (pure rendering, no mutation).
  • You can opt out individual components using the "use no memo" directive.
  • Next, you will explore smooth UI animations across route and state changes using React 19.3’s native <ViewTransition> API!

Frequently asked questions

Is the React Compiler an experimental prototype?

The React Compiler reached Stable 1.0 in late 2025 and powers production apps at Meta (including Instagram and Facebook web). It is officially recommended by the React core team for modern React 19 apps.

Does the compiler increase my final production bundle size?

Minimally. The compiler emits lightweight cache slots. In practice, the tiny increase in bytecode is drastically outweighed by the elimination of runtime re-render lag across your entire app.

Does the React Compiler work with TypeScript?

Yes. The compiler operates at the Babel/Vite transformation level and fully supports both JavaScript (.jsx) and TypeScript (.tsx).

What is react-compiler-healthcheck?

It is an official CLI tool (npx react-compiler-healthcheck) that scans your project files, reports how many components can be compiled successfully, and flags any incompatible patterns before you install the compiler.

Can I use the compiler with Next.js or Remix?

Yes. Major meta-frameworks like Next.js have built-in configuration flags (e.g., experimental.reactCompiler: true in next.config.js) that enable the compiler out of the box.

See also: memo, useMemo and useCallback, How React Renders, React Setup with Vite