Sub topic 2
What Compiled Output Looks Like
Assume you know React function components, props, state, hooks, and a JavaScript build tool. The React Compiler runs during the build. It analyzes components and hooks, then emits JavaScript with memoization logic.
What compiled output looks like
You normally write straightforward code:
function List({ items }) {
const visible = items.filter((item) => item.name.includes('a'));
return <ul>{visible.map((item) => <li key={item.id}>{item.name}</li>)}</ul>;
}The compiler can preserve this source while generating internal caches in the output. Those caches let React reuse calculations, JSX results, and callback references when their inputs have not changed. The exact generated code is an implementation detail, so do not edit it directly.
Fine-grained and conditional memoization
Memoization means reusing a previous value instead of calculating it again. The compiler can memoize smaller parts of a component rather than treating the entire component as one unit. It can also reuse a value only when its dependencies are unchanged.
This is more precise than adding memo to every child and wrapping every calculation in useMemo. It can avoid unnecessary work while still allowing unrelated state to update.
Setting up the Babel plugin
Install babel-plugin-react-compiler, then add it to Babel. The compiler plugin should run first.
// babel.config.js
module.exports = {
plugins: [
['babel-plugin-react-compiler', {}],
],
};For Vite, pass the plugin through @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'],
},
}),
],
});React version support
The compiler supports React 19 directly. React 17 and 18 require the react-compiler-runtime package. Set the compiler target to match the React version your output must run on.
Adopting the compiler gradually
Use annotation mode to compile only functions containing the "use memo" directive. Use "use no memo" to exclude a function while you investigate a problem.
// babel.config.js
module.exports = {
plugins: [
['babel-plugin-react-compiler', {
compilationMode: 'annotation',
target: '18',
}],
],
};Exercise
Why should you avoid depending on the exact generated JavaScript?
Show answer
The compiler may change its internal memoization strategy between versions; verify behavior instead.