<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ React-compiler - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ React-compiler - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 23 Jun 2026 22:45:17 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/react-compiler/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use React Compiler – A Complete Guide ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, you'll learn how the React compiler can help you write more optimized React applications. React is a user interface library that has been doing its job quite well for over a decade. The component architecture, uni-directional data f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-compiler-complete-guide-react-19/</link>
                <guid isPermaLink="false">66ce54c3e498db1304d6a34b</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React 19 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React-compiler ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tapas Adhikary ]]>
                </dc:creator>
                <pubDate>Tue, 27 Aug 2024 22:35:47 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724760187590/f7115fd3-6291-4920-9522-61de269a47f3.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, you'll learn how the React compiler can help you write more optimized React applications.</p>
<p>React is a user interface library that has been doing its job quite well for over a decade. The component architecture, uni-directional data flow, and declarative nature stand out in helping devs building production-ready, scalable software applications.</p>
<p>Over the releases (even up until the latest stable release of v18.x), React has provided various techniques and methodologies to improve application performance.</p>
<p>For example, the entire memoization paradigm has been supported using the <code>React.memo()</code> higher-order component, or with hooks like <code>useMemo()</code> and <code>useCallback()</code>.</p>
<p>In programming, <code>memoization</code> is an optimization technique that makes your programs execute faster by caching the result of expensive computations.</p>
<p>Although React's <code>memoization</code> techniques are great for applying optimizations, as Uncle Ben (remember, Spiderman's uncle?) once said, "With great power comes great responsibility". So we as developers need to be a little more responsible in applying them. Optimization is great, but over-optimization can be a killer for the application's performance.</p>
<p>With React 19, the developer community has received a list of enhancements and features to boast about:</p>
<ul>
<li><p>An experimental open-source compiler. We will be focusing primarily on it in this article.</p>
</li>
<li><p>React Server Components.</p>
</li>
<li><p>Server Actions.</p>
</li>
<li><p>Easier and more organic way of handling the document metadata.</p>
</li>
<li><p>Enhanced hooks and APIs.</p>
</li>
<li><p><code>ref</code> can be passed as props.</p>
</li>
<li><p>Improvements in asset loading for styles, images, and fonts.</p>
</li>
<li><p>A much smoother integration with Web Components.</p>
</li>
</ul>
<p>If these are exciting to you, I recommend <a target="_blank" href="https://www.youtube.com/watch?v=hiiGUjEkzbM">watching this video</a> that explains how each feature will impact you as a React developer. I hope you like it 😊.</p>
<p>The introduction of a <code>compiler</code> with <code>React 19</code> is set to be a game-changer. From now on, we can let the compiler handle the optimization headache rather than keeping it on us.</p>
<p>Does this mean we do not have to use <code>memo</code>, <code>useMemo()</code>, <code>useCallback</code>, and so on anymore? No – we mostly don't. The compiler can take care of these things automatically if you understand and follow the <a target="_blank" href="https://react.dev/reference/rules">Rules of React</a> for components and hooks.</p>
<p>How will it do this? Well, we'll get to it. But before that, let's understand what a <code>compiler</code> is and whether it's justified to call this new optimizer for React code the <code>React Compiler</code>.</p>
<p>If you like to learn from video tutorials as well, this article is also available as a video tutorial here:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/bdWUVp0TbTU" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-a-compiler-traditionally">What is a Compiler, traditionally?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-compiler-architecture">React Compiler Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-compiler-in-action">React Compiler in action</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-the-problem-without-the-react-compiler">Understanding the problem: Without the React Compiler</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-fixing-the-problem-without-the-react-compiler">Fixing the problem: Without the React Compiler</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-fixing-the-problem-using-the-react-compiler">Fixing the problem: Using the React Compiler</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-optimized-react-app-with-react-compiler">Optimized React App with React Compiler</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-compiler-in-react-devtools">React Compiler in React DevTools</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-diving-deep-how-does-the-react-compiler-work">Diving deep - How does the React Compiler work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-do-you-opt-in-and-out-of-the-react-compiler">How do you opt in and out of the React compiler?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-can-we-use-the-react-compiler-with-react-18x">Can we use the React Compiler with React 18.x?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-repositories-to-look-into">Repositories to look into</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-whats-next">What's Next?</a></p>
</li>
</ol>
<h2 id="heading-what-is-a-compiler-traditionally">What is a Compiler, Traditionally?</h2>
<p>Simply put, a compiler is a software program/tool that translates high-level programming language code (source code) into machine code. There are several steps to follow to compile source code and generate machine code:</p>
<ul>
<li><p>The <code>lexical analyzer</code> tokenizes the source code and generates tokens.</p>
</li>
<li><p>The <code>Syntax Analyzer</code> creates an abstract syntax tree (AST) to structure the source code tokens logically.</p>
</li>
<li><p>The <code>Semantic Analyzer</code> validates the semantic (or syntactic) correctness of the code.</p>
</li>
<li><p>After all three types of analysis by the respective analyzers, some <code>intermediate code</code> gets generated. It is also known as the IR code.</p>
</li>
<li><p>Then <code>optimization</code> is performed on the IR code.</p>
</li>
<li><p>Finally, the <code>machine code</code> is generated by the compiler from the optimized IR code.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724227359567/a3994e4c-9018-4b67-94be-8b5f403eceb9.png" alt="Compiler phases as described above" class="image--center mx-auto" width="1200" height="630" loading="lazy"></p>
<p>Now that you understand the basics of how a compiler works, let's learn about the <code>React Compiler</code> and understand how it works.</p>
<h2 id="heading-react-compiler-architecture">React Compiler Architecture</h2>
<p>React compiler is a build-time tool that you need to configure with your React 19 project explicitly using the configuration options provided by the React tools ecosystem.</p>
<p>For example, if you are using <code>Vite</code> to create your React application, the compiler configuration will take place in the <code>vite.config.js</code> file.</p>
<p>React compiler has three primary components:</p>
<ol>
<li><p><code>Babel Plugin</code><strong>:</strong> helps transform the code during the compilation process<strong>.</strong></p>
</li>
<li><p><code>ESLint Plugin</code><strong>:</strong> helps catch and report any violations of the Rules of React.</p>
</li>
<li><p><code>Compiler Core</code>: the core compiler logic that performs the code analysis and optimizations. Both Babel and ESLint plugins use the core compiler logic.</p>
</li>
</ol>
<p>The compilation flow goes like this:</p>
<ul>
<li><p>The <code>Babel Plugin</code> identifies which functions (components or hooks) to compile. We will see some configurations later to learn how to opt in and out of the compilation process. The plugin calls the core compiler logic for each of the functions and finally creates the Abstract Syntax Tree.</p>
</li>
<li><p>Then the compiler core converts the Babel AST into IR code, analyzes it, and runs various validations to ensure none of the rules are broken.</p>
</li>
<li><p>Next, it tries to reduce the amount of code to be optimized by performing various passes to eliminate dead code. The code gets further optimized using memoization.</p>
</li>
<li><p>Finally, in the code generation stage, the transformed AST is converted back to the optimized JavaScript code.</p>
</li>
</ul>
<h2 id="heading-react-compiler-in-action">React Compiler in Action</h2>
<p>Now that you know how React Compiler works, let's now dive into configuring it with a React 19 project so you can start learning about the various optimizations.</p>
<h3 id="heading-understanding-the-problem-without-the-react-compiler">Understanding the problem: Without the React Compiler</h3>
<p>Let's create a simple product page with React. The product page shows a heading with the number of products on the page, a list of products, and the featured products.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724240252940/bd5118d1-2819-4119-ac96-57e267742432.png" alt="The Product Page" class="image--center mx-auto" width="744" height="914" loading="lazy"></p>
<p>The component hierarchy and the data passing between the components look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724240027326/0a8a653d-9c6a-43ff-9457-81dde019e56e.png" alt="Product Page Component Hierarchy" class="image--center mx-auto" width="1456" height="976" loading="lazy"></p>
<p>As you can see in the image above,</p>
<ul>
<li><p>The <code>ProductPage</code> component has three child components, <code>Heading</code>, <code>ProductList</code>, and <code>FeaturedProducts</code>.</p>
</li>
<li><p>The <code>ProductPage</code> component receives two props, <code>products</code> and the <code>heading</code>.</p>
</li>
<li><p>The <code>ProductPage</code> component computes the total number of products and passes the value along with the heading text value to the <code>Heading</code> component.</p>
</li>
<li><p>The <code>ProductPage</code> component passes down the <code>products</code> prop to the <code>ProductList</code> child component.</p>
</li>
<li><p>Similarly, it computes the featured products and passes the <code>featuredProducts</code> prop to the <code>FeaturedProducts</code> child component.</p>
</li>
</ul>
<p>Here is how the source code of the <code>ProductPage</code> component may look:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-keyword">import</span> Heading <span class="hljs-keyword">from</span> <span class="hljs-string">'./Heading'</span>;
<span class="hljs-keyword">import</span> FeaturedProducts <span class="hljs-keyword">from</span> <span class="hljs-string">'./FeaturedProducts'</span>;
<span class="hljs-keyword">import</span> ProductList <span class="hljs-keyword">from</span> <span class="hljs-string">'./ProductList'</span>;

<span class="hljs-keyword">const</span> ProductPage = <span class="hljs-function">(<span class="hljs-params">{products, heading}</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> featuredProducts = products.filter(<span class="hljs-function"><span class="hljs-params">product</span> =&gt;</span> product.featured);
  <span class="hljs-keyword">const</span> totalProducts = products.length;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"m-2"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Heading</span>
        <span class="hljs-attr">heading</span>=<span class="hljs-string">{heading}</span>
        <span class="hljs-attr">totalProducts</span>=<span class="hljs-string">{totalProducts}</span> /&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">ProductList</span>
        <span class="hljs-attr">products</span>=<span class="hljs-string">{products}</span> /&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">FeaturedProducts</span>
        <span class="hljs-attr">featuredProducts</span>=<span class="hljs-string">{featuredProducts}</span> /&gt;</span>  

    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ProductPage
</code></pre>
<p>Also, assume we use the <code>ProductPage</code> component in the <code>App.js</code> file like this:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> ProductPage <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/compiler/ProductPage"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-comment">// A list of food products    </span>
  <span class="hljs-keyword">const</span> foodProducts = [
    {
      <span class="hljs-string">"id"</span>: <span class="hljs-string">"001"</span>,
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"Hamburger"</span>,
      <span class="hljs-string">"image"</span>: <span class="hljs-string">"🍔"</span>,
      <span class="hljs-string">"featured"</span>: <span class="hljs-literal">true</span>
    },
    {
      <span class="hljs-string">"id"</span>: <span class="hljs-string">"002"</span>,
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"French Fries"</span>,
      <span class="hljs-string">"image"</span>: <span class="hljs-string">"🍟"</span>,
      <span class="hljs-string">"featured"</span>: <span class="hljs-literal">false</span>
    },
    {
      <span class="hljs-string">"id"</span>: <span class="hljs-string">"003"</span>,
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"Taco"</span>,
      <span class="hljs-string">"image"</span>: <span class="hljs-string">"🌮"</span>,
      <span class="hljs-string">"featured"</span>: <span class="hljs-literal">false</span>
    },
    {
      <span class="hljs-string">"id"</span>: <span class="hljs-string">"004"</span>,
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"Hot Dog"</span>,
      <span class="hljs-string">"image"</span>: <span class="hljs-string">"🌭"</span>,
      <span class="hljs-string">"featured"</span>: <span class="hljs-literal">true</span>
    }
  ];

  <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ProductPage</span> 
            <span class="hljs-attr">products</span>=<span class="hljs-string">{foodProducts}</span> 
            <span class="hljs-attr">heading</span>=<span class="hljs-string">"The Food Product"</span> /&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>That's all good – so where is the problem? The problem is that React proactively re-renders the child component when the parent component re-renders. An unnecessary rendering requires optimizations. Let's understand the problem fully first.</p>
<p>We'll add the current timestamp in each of the child components. Now the rendered user interface will look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724241332454/5debcdce-0349-40a3-916f-78e479668c12.png" alt="With timestamp" class="image--center mx-auto" width="1374" height="926" loading="lazy"></p>
<p>The big number you see beside the headings is the timestamp (using the simple <code>Date.now()</code> function from the JavaScript Date API) we have added to the component code. Now what happens if we change the value of the heading prop of the <code>ProductPage</code> component?</p>
<p>Before:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">ProductPage</span> 
   <span class="hljs-attr">products</span>=<span class="hljs-string">{foodProducts}</span> 
   <span class="hljs-attr">heading</span>=<span class="hljs-string">"The Food Product"</span> /&gt;</span>
</code></pre>
<p>And after (notice that we have made it plural for products by adding an <code>s</code> at the end of the <code>heading</code> value):</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">ProductPage</span> 
   <span class="hljs-attr">products</span>=<span class="hljs-string">{foodProducts}</span> 
   <span class="hljs-attr">heading</span>=<span class="hljs-string">"The Food Products"</span> /&gt;</span>
</code></pre>
<p>Now you will notice an immediate change in the user interface. All three timestamps got updated. This is because all three components were re-rendered when the parent component was re-rendered due to the props change.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724242207319/b3f2aa7e-d387-4de4-a2e6-9491f5cf7996.png" alt="compiler diff" class="image--center mx-auto" width="1200" height="630" loading="lazy"></p>
<p>If you notice, the <code>heading</code> prop was passed only to the <code>Heading</code> component, and even then the other two child components re-rendered. This is where we need the optimizations.</p>
<h3 id="heading-fixing-the-problem-without-the-react-compiler">Fixing the Problem: Without the React Compiler</h3>
<p>As discussed before, React provides us with various hooks and APIs for <code>memoization</code>. We can use <code>React.memo()</code> or <code>useMemo()</code> to safeguard the components that are re-rendering unnecessarily.</p>
<p>For example, we can use <code>React.memo()</code> to memoize the ProductList component to ensure that unless the <code>products</code> prop is changed, the <code>ProductList</code> component will not be re-rendered.</p>
<p>We can use the <code>useMemo()</code> hook to memoize the computation for the featured products. Both implementations are indicated in the image below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724242889553/ec0d54fc-8c50-4fef-a4ea-e8c5951da9ad.png" alt="Applying memoization" class="image--center mx-auto" width="2462" height="1318" loading="lazy"></p>
<p>But again, recollecting the wise words of great Uncle Ben, over the last few years we have started over-using these optimization techniques. These over-optimizations can negatively impact the performance of your applications. So, the availability of the compiler is a boon for React developers as it lets them delegate many such optimizations to the compiler.</p>
<p>Let's now fix the problem using the React compiler.</p>
<h3 id="heading-fixing-the-problem-using-the-react-compiler">Fixing the problem: Using the React Compiler</h3>
<p>Again, React compiler is an opt-in build-time tool. It doesn't come bundled with React 19 RC. You need to install the required dependencies and configure the compiler with your React 19 project.</p>
<p>Before configuring the compiler, you can check if your codebase is compatible by executing this command on your project directory:</p>
<pre><code class="lang-bash">npx react-compiler-healthcheck@experimental
</code></pre>
<p>It will check and report:</p>
<ul>
<li><p>How many components can be optimized by the compiler</p>
</li>
<li><p>If the Rules of React are followed.</p>
</li>
<li><p>If there are any incompatible libraries.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724300204675/d7866215-5cda-4a64-b0d6-ecedb100a428.png" alt="d7866215-5cda-4a64-b0d6-ecedb100a428" class="image--center mx-auto" width="1832" height="448" loading="lazy"></p>
<p>If you find that things are compatible, it's time to install the ESLint plugin powered by the React compiler. This plugin will help you catch any violation of the rules of React in your code. Violating code will be skipped by the React compiler and no optimizations will be performed on it.</p>
<pre><code class="lang-bash">npm install eslint-plugin-react-compiler@experimental
</code></pre>
<p>Then open the ESLint configuration file (for example, <code>.eslintrc.cjs</code> for Vite) and add these configurations:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">plugins</span>: [
    <span class="hljs-string">'eslint-plugin-react-compiler'</span>,
  ],
  <span class="hljs-attr">rules</span>: {
    <span class="hljs-string">'react-compiler/react-compiler'</span>: <span class="hljs-string">"error"</span>,
  },
}
</code></pre>
<p>Next, you'll use the Babel plugin for the React compiler to enable the compiler for your entire project. If you're starting a new project with React 19, I recommend that you enable the React compiler for the entire project. Let's install the Babel plugin for the React compiler:</p>
<pre><code class="lang-bash">npm install babel-plugin-react-compiler@experimental
</code></pre>
<p>Once installed, you need to complete the configuration by adding the options in the Babel config file. As we're using Vite, open the <code>vite.config.js</code> file and replace the content with the following code snippet:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">'@vitejs/plugin-react'</span>

<span class="hljs-keyword">const</span> ReactCompilerConfig = {<span class="hljs-comment">/* ... */</span> };

<span class="hljs-comment">// https://vitejs.dev/config/</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
  <span class="hljs-attr">plugins</span>: [react({
    <span class="hljs-attr">babel</span>: {
      <span class="hljs-attr">plugins</span>: [
        [
          <span class="hljs-string">"babel-plugin-react-compiler"</span>,
           ReactCompilerConfig
          ]
        ],
    },
  })],
})
</code></pre>
<p>Here, you've added the <code>babel-plugin-react-compiler</code> to the configuration. The <code>ReactCompilerConfig</code> is required to provide any advanced configuration like if you want to provide any custom runtime module or any other configurations. In this case, it's an empty object without any advanced configurations.</p>
<p>That's it. You are done configuring the React compiler with your code base to utilize its power. From now on, the React compiler will look into every component and hook in your project to try and apply optimizations to it.</p>
<p>If you want to configure the React compiler with Next.js, Remix, Webpack, and so on, you can <a target="_blank" href="https://react.dev/learn/react-compiler#installation">follow this guide</a>.</p>
<h3 id="heading-optimized-react-app-with-react-compiler">Optimized React App with React Compiler</h3>
<p>Now you should have an optimized React app with the inclusion of the React compiler. So, let's run the same tests you did before. Again, change the value of the <code>heading</code> prop of the <code>ProductPage</code> component.</p>
<p>This time, you will not see the child components re-rendering. So the timestamp will not be updated either. But you will see the portion of the component where the data changed, as it will reflect the changes alone. Also, you won't have to use <code>memo</code>, <code>useMemo()</code>, or <code>useCallback()</code> in your code anymore.</p>
<p>You can see it working visually <a target="_blank" href="https://youtu.be/bdWUVp0TbTU?t=1326">from here</a>.</p>
<h2 id="heading-react-compiler-in-react-devtools">React Compiler in React DevTools</h2>
<p><a target="_blank" href="https://react.dev/learn/react-developer-tools">React DevTools</a> version 5.0+ has built-in support for the React compiler. You will see a badge with the text <code>Memo ✨</code> beside the components optimized by the React compiler. This is fantastic!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724303700810/2888b91c-bcec-4da2-88a6-840c51876d83.png" alt="React DevTools" class="image--center mx-auto" width="2412" height="1302" loading="lazy"></p>
<h2 id="heading-diving-deep-how-does-the-react-compiler-work">Diving Deep – How Does the React Compiler Work?</h2>
<p>Now that you've seen how the React compiler works on React 19 code, let's deep dive into understanding what's happening in the background. We will use the React <a target="_blank" href="https://playground.react.dev/">Compiler Playground</a> to explore the translated code and the optimization steps.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724740109843/a5047d83-4407-491f-8e11-6522c1381313.png" alt="React Compiler Playground" class="image--center mx-auto" width="2998" height="1394" loading="lazy"></p>
<p>We'll use the <code>Heading</code> component as an example. Copy and paste the following code inside the leftmost section of the playground:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> Heading = <span class="hljs-function">(<span class="hljs-params">{ heading, totalProducts }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-2xl"</span>&gt;</span>
          {heading}({totalProducts}) - {Date.now()}
      <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span></span>
  )
}
</code></pre>
<p>You will see that some JavaScript code is generated immediately inside the <code>_JS</code> tab of the playground. The React compiler generates this JavaScript code as part of the compilation process. Let's go over it step-by-step:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">anonymous_0</span>(<span class="hljs-params">t0</span>) </span>{
  <span class="hljs-keyword">const</span> $ = _c(<span class="hljs-number">4</span>);
  <span class="hljs-keyword">const</span> { heading, totalProducts } = t0;
  <span class="hljs-keyword">let</span> t1;
  <span class="hljs-keyword">if</span> ($[<span class="hljs-number">0</span>] === <span class="hljs-built_in">Symbol</span>.for(<span class="hljs-string">"react.memo_cache_sentinel"</span>)) {
    t1 = <span class="hljs-built_in">Date</span>.now();
    $[<span class="hljs-number">0</span>] = t1;
  } <span class="hljs-keyword">else</span> {
    t1 = $[<span class="hljs-number">0</span>];
  }
  <span class="hljs-keyword">let</span> t2;
  <span class="hljs-keyword">if</span> ($[<span class="hljs-number">1</span>] !== heading || $[<span class="hljs-number">2</span>] !== totalProducts) {
    t2 = (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-2xl"</span>&gt;</span>
          {heading}({totalProducts}) - {t1}
        <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span></span>
    );
    $[<span class="hljs-number">1</span>] = heading;
    $[<span class="hljs-number">2</span>] = totalProducts;
    $[<span class="hljs-number">3</span>] = t2;
  } <span class="hljs-keyword">else</span> {
    t2 = $[<span class="hljs-number">3</span>];
  }
  <span class="hljs-keyword">return</span> t2;
}
</code></pre>
<p>The compiler uses a hook called <code>_c()</code> to create an array of items to cache. In the code above, an array of four elements has been created to cache four items.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> $ = _c(<span class="hljs-number">4</span>);
</code></pre>
<p>But, what are the things to cache?</p>
<ul>
<li><p>The component takes two props, <code>heading</code> and <code>totalProducts</code>. The compiler needs to cache them. So, it needs two elements in the array of cacheable items.</p>
</li>
<li><p>The <code>Date.now()</code> part in the header should be cached.</p>
</li>
<li><p>The JSX itself should be cached. There is no point in computing JSX unless either of the above changes.</p>
</li>
</ul>
<p>So there are a total of four items to cache.</p>
<p>The compiler creates memoization blocks using the <code>if-block</code>. The final return value from the compiler is the JSX which depends on three dependencies:</p>
<ul>
<li><p>The <code>Date.now()</code> value.</p>
</li>
<li><p>Two props, a <code>heading</code> and <code>totalProducts</code></p>
</li>
</ul>
<p>The output JSX needs re-computation when any of the above changes. This means that the compiler needs to create two memoization blocks for each of the above.</p>
<p>The first memoization block looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> ($[<span class="hljs-number">0</span>] === <span class="hljs-built_in">Symbol</span>.for(<span class="hljs-string">"react.memo_cache_sentinel"</span>)) {
    t1 = <span class="hljs-built_in">Date</span>.now();
    $[<span class="hljs-number">0</span>] = t1;
} <span class="hljs-keyword">else</span> {
    t1 = $[<span class="hljs-number">0</span>];
}
</code></pre>
<p>The if-block stores the value of the Date.now() into the first index of the cacheable array. It re-uses the same every time unless it is changed.</p>
<p>Similarly, in the second memoization block:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> ($[<span class="hljs-number">1</span>] !== heading || $[<span class="hljs-number">2</span>] !== totalProducts) {
    t2 = (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-2xl"</span>&gt;</span>
          {heading}({totalProducts}) - {t1}
        <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span></span>
    );
    $[<span class="hljs-number">1</span>] = heading;
    $[<span class="hljs-number">2</span>] = totalProducts;
    $[<span class="hljs-number">3</span>] = t2;
  } <span class="hljs-keyword">else</span> {
    t2 = $[<span class="hljs-number">3</span>];
  }
</code></pre>
<p>Here, the check is for the value changes for either <code>heading</code> or <code>totalProducts</code> props. If either of these changes, the JSX needs to be recomputed. All the values are then stored in the cacheable array. If there are no changes in the value, the previously computed JSX is returned from the cache.</p>
<p>You can now paste any other component source code into the left side and look into the generated JavaScript code to help you understand what's going on as we did above. This will help you to get a better grip on how the compiler performs the memoization techniques in the compilation process.</p>
<h2 id="heading-how-do-you-opt-in-and-out-of-the-react-compiler">How Do You Opt in and Out of the React Compiler?</h2>
<p>Once you've configured the React compiler the way we have done with our Vite project here, it's enabled for all the compilers and hooks of the project.</p>
<p>But in some cases, you may want to selectively opt-in for the React compiler. In that case, you can run the compiler in “opt-in” mode using the <code>compilationMode: "annotation"</code> option.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Specify the option in the ReactCompilerConfig</span>
<span class="hljs-keyword">const</span> ReactCompilerConfig = {
  <span class="hljs-attr">compilationMode</span>: <span class="hljs-string">"annotation"</span>,
};
</code></pre>
<p>Then annotate the components and hooks you want to opt-in for compilation with the <code>"use memo"</code> directive.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// src/ProductPage.jsx</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductPage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-string">"use memo"</span>;
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>Note that there is a <code>"use no memo"</code> directive as well. There might be some rare cases where your component may not be working as expected after compilation, and you want to opt out of the compilation temporarily until the issue is identified and fixed. In that case, you can use this directive:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-string">"use no memo"</span>;
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<h2 id="heading-can-we-use-the-react-compiler-with-react-18x">Can We Use the React Compiler with React 18.x?</h2>
<p>It is recommended to use the React compiler with React 19 as there are required compatibilities. If you can't upgrade your application to React 19, you'll need to have a custom implementation of the cache function. You can go over <a target="_blank" href="https://github.com/reactwg/react-compiler/discussions/6">this thread</a> describing the workaround.</p>
<h3 id="heading-repositories-to-look-into">Repositories to Look Into</h3>
<ul>
<li><p>All the source code used in this article is <a target="_blank" href="https://github.com/tapascript/react-compiler-lesson">in this repository</a>.</p>
</li>
<li><p>If you want to start coding with React 19 and its features, <a target="_blank" href="https://github.com/atapas/code-in-react-19">here is a template repository</a> configured with React 19 RC, Vite, and TailwindCSS. You may want to try it out.</p>
</li>
</ul>
<h2 id="heading-whats-next">What's Next?</h2>
<p>To learn further,</p>
<ul>
<li><p>Check out the official documentation of React Compiler <a target="_blank" href="https://react.dev/learn/react-compiler">from here</a>.</p>
</li>
<li><p>Check out the <a target="_blank" href="https://github.com/reactwg/react-compiler/discussions">discussions</a> in the Working Group.</p>
</li>
</ul>
<p>Up next, if you are willing to learn <code>React</code> and its ecosystem-like <code>Next.js</code> with both fundamental concepts and projects, I have great news for you: you can <a target="_blank" href="https://www.youtube.com/watch?v=VSB2h7mVhPg&amp;list=PLIJrr73KDmRwz_7QUvQ9Az82aDM9I8L_8">check out this playlist on my YouTube</a> channel with 22+ video tutorials and 12+ hours of engaging content so far, for free. I hope you like them as well.</p>
<p>That's all for now. Did you enjoy reading this article and have you learned something new? If so, I would love to know if the content was helpful.</p>
<ul>
<li><p>Subscribe to my <a target="_blank" href="https://www.youtube.com/tapasadhikary?sub_confirmation=1">YouTube Channel</a>.</p>
</li>
<li><p><a target="_blank" href="https://twitter.com/tapasadhikary">Follow me on X (Twitter</a>) or <a target="_blank" href="https://www.linkedin.com/in/tapasadhikary/">LinkedIn</a> if you don't want to miss the daily dose of up-skilling tips.</p>
</li>
<li><p>Check out and follow my Open Source work on <a target="_blank" href="https://github.com/atapas">GitHub</a>.</p>
</li>
<li><p>I regularly publish meaningful posts on my <a target="_blank" href="https://blog.greenroots.info/">GreenRoots Blog</a>, you may find them helpful, too.</p>
</li>
</ul>
<p>See you soon with my next article. Until then, please take care of yourself, and keep learning.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
