What is the React Compiler?
- React course
- Expert
- Lesson 1/32
- 4 min
Learn that the new React Compiler offers automatic memoization.
What is the React Compiler?
The React Compiler is a tool that adds automatic memoization during compilation. You no longer need to write useMemo or useCallback; the compiler prevents unnecessary recalculations itself.
It runs as a Babel plugin and analyses each component. When a value's dependencies are unchanged it reuses the old result. This keeps code simple and improves performance.
It is not yet default in all projects; you can opt in.
Babel plugin and configuration
To enable the compiler you add the babel-plugin-react-compiler package to your Babel config. In Next.js the reactCompiler: true option is enough.
The compiler only memoizes safe code; it skips impure render output. Therefore your components must be pure.
Legacy projects can migrate gradually; each file can be opted in separately.
Practice Write the PriceList component
Write a PriceList component. Take an items prop. Compute total with items.reduce. Inside a <div> show <h1>{total}</h1> and inside a <ul> map items to <li key={item.id}>{item.name}</li>. Export it.
Starter code
// Write the PriceList component hereSample solution
function PriceList({ items }) {
const total = items.reduce((sum, item) => sum + item.price, 0);
return (
<div>
<h1>{total}</h1>
<ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>
</div>
);
}
export default PriceList;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the React Compiler do?
- Minifies and compresses code
- Adds automatic memoization during compilation Correct answer
- Generates TypeScript types
- Renders components on the server
Explanation: The compiler prevents unnecessary calculations.
2 Fill in the blank: enable the compiler
module.exports = {
babel: {
plugins: [['babel-plugin-react-compiler', { ____: true }]],
},
};
module.exports = {
babel: {
plugins: [['babel-plugin-react-compiler', { compilation: true }]],
},
};
Explanation: true starts the compiler.
3 Match compiler concepts
| Term | Meaning |
|---|---|
auto memoization |
Prevents needless calc |
Babel plugin |
Includes in build |
pure render |
Can be memoized |
dependencies |
Unchanged reuses old |