React Compiler
Overview
The previous lesson showed how memo, useMemo and useCallback can skip unnecessary work — and how fiddly they are to get right. React Compiler does it automatically. It’s a build-time tool, stable since version 1.0, that reads your components and rewrites them to memoise exactly what can be memoised. You write plain, readable React; the compiled output is optimised.
What the compiler does
Consider:
function CourseList({ courses, query, onOpen }) {
const visible = courses.filter((c) => c.title.toLowerCase().includes(query.toLowerCase()));
return <List items={visible} onPick={(id) => onOpen(id)} />;
}Without the compiler, every render recomputes visible, creates a new onPick function, and re-renders List. With the compiler, the output (simplified) behaves like:
- if
coursesandqueryare unchanged → reuse the previousvisible, - if
onOpenis unchanged → reuse the previousonPick, - if
visibleandonPickare unchanged → reuse the previous<List>element, so React skips re-rendering it.
It memoises at a finer grain than you’d normally bother to by hand — individual values and JSX elements, even after early returns.
Setting it up with Vite
Vite 8 projects use @vitejs/plugin-react 6, which offers a ready-made Babel preset for the compiler:
npm install -D @rolldown/plugin-babel @babel/core babel-plugin-react-compiler// vite.config.js
import babel from '@rolldown/plugin-babel';
import react, { reactCompilerPreset } from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [react(), babel({ presets: [reactCompilerPreset()] })],
});That’s it — restart the dev server. In React DevTools, compiled components show a Memo ✨ badge next to their name.
@vitejs/plugin-reactalso has an experimentalcompiler: trueoption that uses a faster Rust port of the compiler. The Babel setup above is the stable route.
Other setups:
- Next.js: set
reactCompiler: trueinnext.config.js(and installbabel-plugin-react-compiler). - React Router framework mode / other Babel-based tools: add
babel-plugin-react-compilerto the Babel plugins. - React 17 or 18: supported with the
targetoption and thereact-compiler-runtimepackage.
Linting: the compiler’s companion
The compiler’s checks are also available as lint rules in eslint-plugin-react-hooks (version 7+ includes the compiler-powered rules in its recommended config). They flag code the compiler can’t optimise — mutating props, reading refs during render, calling hooks conditionally, setting state during render — while you type. Enable them even before turning the compiler on; they catch real bugs.
// eslint.config.js
import reactHooks from 'eslint-plugin-react-hooks';
import { defineConfig } from 'eslint/config';
export default defineConfig([
reactHooks.configs.flat.recommended,
]);The Rules of React
The compiler can only optimise code it can prove is safe. That means following the Rules of React — which you’ve been learning throughout this course:
- Components and hooks must be pure. Same props and state → same output; no side effects during render.
- Props and state are immutable. Never mutate them; create new values.
- Hook arguments and return values are immutable once passed.
- Don’t mutate values after passing them to JSX.
- Only call hooks at the top level, from React functions.
- Don’t read or write
ref.currentduring render.
When the compiler detects a violation, it skips that component and leaves it exactly as written — your app keeps working, that component just isn’t memoised. The lint rules report the same problem:
// ✗ Assigns to a prop — detected: lint error, component left uncompiled
function CourseTitle({ course }) {
course.title = course.title.trim();
return <h2>{course.title}</h2>;
}But not every violation can be detected. A mutating method call on a prop slips through:
// ✗ Mutates a prop with sort() — NOT detected, so it gets compiled
function CourseList({ courses, sortBy }) {
courses.sort((a, b) => a[sortBy].localeCompare(b[sortBy]));
return <ul>{courses.map((c) => <li key={c.id}>{c.title}</li>)}</ul>;
}The compiler assumes courses can’t change unless its identity changes, so it caches the list and only rebuilds it when a new courses array arrives. Change sortBy and the component re-renders — but shows the old order. Code that “worked” without the compiler now has a real bug. The fix is the same as always: don’t mutate, derive.
// ✓ Derives a new array — correct with or without the compiler
function CourseList({ courses, sortBy }) {
const sorted = courses.toSorted((a, b) => a[sortBy].localeCompare(b[sortBy]));
return <ul>{sorted.map((c) => <li key={c.id}>{c.title}</li>)}</ul>;
}That’s why following the rules matters more than ever: the lint rules and the compiler catch a lot, but not everything.
Adopting it gradually
For an existing codebase:
- Turn on the lint rules and fix the violations they report.
- Enable the compiler and test your app — code that broke the rules in ways the tools can’t detect may have “worked by accident” and behave differently once memoised (like the
sort()example above). - If one component causes trouble, opt it out with the
"use no memo"directive while you fix it:
function LegacyWidget() {
'use no memo';
// …
}You can also start with compilationMode: 'annotation', which only compiles components marked with "use memo", then switch to compiling everything.
What about existing useMemo and useCallback?
You don’t need to delete them — the compiler works alongside them. In new code, you can write without them and let the compiler handle memoisation. Two cases still call for manual tools:
- Effect dependencies where you need a guaranteed-stable value regardless of compilation — keep
useMemo/useCallbackthere, or restructure. - Truly expensive work that you want to control explicitly.
What the compiler doesn’t do
The compiler reduces unnecessary re-rendering and recomputation. It doesn’t:
- make a genuinely expensive render cheaper (sorting 50,000 rows is still slow — memoised or not, it runs whenever the data changes),
- shrink your bundle or speed up network requests,
- fix slow typing caused by rendering huge lists — that’s what transitions and virtualisation are for (next lesson).
The big win is simplicity. With React Compiler on, you write the obvious code, and performance follows — as long as your components play by the Rules of React.
Enable the compiler and fix a violation
Add React Compiler to your Vite project with @rolldown/plugin-babel and reactCompilerPreset, and turn on the React Hooks lint rules. Then fix the Rules of React violation in this component: it mutates a prop while rendering. Neither the linter nor the compiler can detect this kind of mutation, so with the compiler on, the list would keep its old order when sortBy changes. Confirm in React DevTools that the component shows the Memo ✨ badge.
# 1. install and configure the compiler (vite.config.js)
# 2. fix this component:
# function CourseList({ courses, sortBy }) {
# courses.sort((a, b) => a[sortBy].localeCompare(b[sortBy]));
# return <ul>{courses.map((c) => <li key={c.id}>{c.title}</li>)}</ul>;
# }npm install -D @rolldown/plugin-babel @babel/core babel-plugin-react-compiler
npm install -D eslint eslint-plugin-react-hooks # if you use ESLint
# vite.config.js
# import babel from '@rolldown/plugin-babel';
# import react, { reactCompilerPreset } from '@vitejs/plugin-react';
# import { defineConfig } from 'vite';
#
# export default defineConfig({
# plugins: [react(), babel({ presets: [reactCompilerPreset()] })],
# });
# Fixed component — derive a new sorted array instead of mutating the prop:
# function CourseList({ courses, sortBy }) {
# const sorted = courses.toSorted((a, b) => a[sortBy].localeCompare(b[sortBy]));
# return <ul>{sorted.map((c) => <li key={c.id}>{c.title}</li>)}</ul>;
# }Summary
- React Compiler is a build-time tool that automatically memoizes components, values and functions.
- It removes the need for most manual
memo,useMemoanduseCallback, and is often more precise than hand-written memoisation. - In a Vite 8 project, enable it with
@rolldown/plugin-babeland thereactCompilerPresetfrom@vitejs/plugin-react. - It relies on the Rules of React: pure rendering, no mutation of props or state, hooks called correctly.
- Detected rule violations make it skip a component; undetected ones (like
props.items.sort()) can turn into stale-UI bugs.