logo

The New 2024 React Compiler

Excited and Skeptical about React Compiler

May 24, 2024 (8mo ago)

I just finished watching React Conf 2024, I want to tell you what this compiler does and what were the main key points mentioned in that conf.

The Power of this Compiler

React automatically re-renders the whole component when state changes, and that's not a good idea.

React Compiler

This compiler auto-memoize your react code.

Compiler

Before, you had to use useMemo() and useCallback() but now that compiler does automatically that for you.

Compiler

Honestly, I never liked those hooks and the reality I never used them.

React hears to my instincts and I knew before that manual memoization is very hard in large scale projects.

You might use React Compiler for...
Dead Code Elimination
Fewer Lines
Better Performance
Faster Apps
Skipping re-renders
Skipping Expensive Calculations

It's a good practice to see the compiled react code to understand the logic behind that compiler, Go to React Playground

React Compiler

Mofei showed that the compiler does auto memoization but not actually by adding useMemo()s, that's just for readability.

Jack explained it very well too and he showed a deep dive into how the compiler process your react code and how it creates an array of slots into chunks of nodes and find what static and what's dynamic and what has to be memoized to avoid unecessary re-renders.

Meta has been using this compiler for over a year now for Instagram web version and Quest apps and this is what they recognized in terms of performance:

Insta React Compiler Performance

It's Open Source

React Compiler is Now Open Source, Give it a Try:

npm i babel-plugin-react-compiler --save-exact

ESLint Plugin for Easy Debugging

React Compiler comes with an ESLint plugin to easy debug your code, it is well trained on the The Rules of React, make sure you write well-written code to get the full benefits:

npm i eslint-plugin-react-compiler --save-exact

It's not Perfect Yet

You might not use React Compiler for such reasons...
Only supports Babel
Extensive Memory Usage
not compatible with MobX
  • As of now, React Compiler only supports Babel and the React Core Team is working on to support SWC for lovers.

NextJS Reaction

NextJS 15 RC was announced yesterday with:

Support for the React 19 RC, React Compiler (Experimental), and hydration error improvements

npm install next@rc react@rc react-dom@rc
next.config.ts
const nextConfig = {
  experimental: {
    reactCompiler: true,
  },
};
 
module.exports = nextConfig;
⚠️

The React Compiler is currently only possible to use in Next.js through a Babel plugin, which could result in slower build times.

Conclusion

React Compiler opens the door to so many opportunities to many more optimization techniques for well-written efficient maintainable scalable code by default optimized for better performance and faster apps with fewer lines of code.

To learn more, Go to React Compiler Doc.