<?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 19 - 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 19 - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 16:31:48 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/react-19/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ New React 19 Features You Should Know –  Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ React.js is 11 years old, and it has become one of the most popular JavaScript libraries out there. And now, React is transitioning from version 18 to version 19. So hold onto your hats, React enthusiasts 🎩. React 19 has recently landed, and it’s a ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/new-react-19-features-you-should-know-with-code-examples/</link>
                <guid isPermaLink="false">66faefcb4098ec2dc4763c03</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React 19 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Prankur Pandey ]]>
                </dc:creator>
                <pubDate>Mon, 30 Sep 2024 18:36:59 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727367514092/a75164cd-1e2e-4b0d-8c2e-5d000cee01f0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React.js is 11 years old, and it has become one of the most popular JavaScript libraries out there.</p>
<p>And now, React is transitioning from version 18 to version 19. So hold onto your hats, React enthusiasts 🎩. React 19 has recently landed, and it’s a game-changer.</p>
<p>But before you start worrying about a steep learning curve, here’s some great news: React 19 isn’t about adding complexity – it’s about removing it.</p>
<p>In this guide, you’ll learn how this new version will simplify your coding life and turbocharge your React projects.</p>
<h2 id="heading-what-well-cover">What We’ll Cover:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-introduction-to-react-19">Introduction to React 19</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-well-cover">What We’ll Cover:</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-19-features">React 19 Features</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-compiler-the-magic-behind-the-scenes">React Compiler: The Magic Behind the Scenes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-no-more-memoization-hooks">No More Memoization Hooks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-no-forwardref-simplified-ref-handling">No forwardRef: Simplified Ref Handling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-new-use-hook-a-game-changer">The New use() Hook: A Game Changer</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-fetch-data-with-use-vs-useeffect">Fetch Data with use() vs. useEffect</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-context-with-use">Use Context with use()</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-directives-a-fresh-approach">Directives: A Fresh Approach</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-actions-streamlined-form-handling">Actions: Streamlined Form Handling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-useformstatus-managing-form-state">useFormStatus(): Managing Form State</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-useformstate-stateful-form-actions">useFormState(): Stateful Form Actions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-useoptimistic-enhancing-user-experience">useOptimistic(): Enhancing User Experience</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<p>Excited to try out React 19? 🤩 While it's still in the canary stage, you can start experimenting with it by installing the canary version today. This update promises a smoother experience by automating what used to be manual optimizations.</p>
<h2 id="heading-react-compiler-the-magic-behind-the-scenes"><strong>React Compiler: The Magic Behind the Scenes</strong></h2>
<p>The star of React 19 is its new compiler. 🎉 This compiler transforms your React code into plain JavaScript, which boosts performance and, even better, frees you from constantly tweaking performance manually.</p>
<p>To optimize our React applications, we use some inbuilt methods like <code>useMemo</code> or <code>useCallback</code>. This tells React not to compile the code again if the inputs don’t change.</p>
<p>But if you forget to apply memoization, it results in wasting React resources and computational power. To deal with this, React 19 introduced React Compiler.</p>
<p>Say goodbye to manual optimizations and hello to cleaner code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// No need for useCallback/useMemo</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Component</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Optimized!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p><strong>Code explanation:</strong> The new compiler turns React code into optimized JavaScript, removing the need for manual optimizations like memoization.</p>
<h2 id="heading-no-more-memoization-hooks"><strong>No More Memoization Hooks</strong></h2>
<p>Remember the days of juggling between <code>useCallback</code>, <code>useMemo</code>, and <code>memo</code> to optimize performance? 😅 With React 19, those days are over. The new compiler optimizes your code behind the scenes, so you can drop these hooks and focus on writing beautiful, clean React components.</p>
<p>Memoization solves the complex calculation problems inside React, resulting in application optimization and performance improvements.</p>
<p>Previously, to apply Memoziation you had to use the <code>useMemo</code> hook. Here’s what that looked like in code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//React 18 </span>
<span class="hljs-keyword">import</span> React, { useState, useMemo } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> ExpensiveComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);
  <span class="hljs-keyword">const</span> [input, setInput] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-comment">// Memoize expensive calculation</span>
  <span class="hljs-keyword">const</span> expensiveCalculation = useMemo(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Calculating..."</span>);
    <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {
      sum += i;
    }
    <span class="hljs-keyword">return</span> sum;
  }, [count]); <span class="hljs-comment">// Recalculate only when `count` changes</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Expensive Calculation: {expensiveCalculation}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;Increment Count ({count})<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> 
        <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> 
        <span class="hljs-attr">value</span>=<span class="hljs-string">{input}</span> 
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setInput(e.target.value)} 
        placeholder="Type something"
      /&gt;
    <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> ExpensiveComponent;
</code></pre>
<p><strong>Code Explanation</strong>:</p>
<ul>
<li><p>The <code>expensiveCalculation</code> the function is computationally heavy, but using <code>useMemo</code>, it's only recalculated when <code>count</code> changes.</p>
</li>
<li><p>The input field can be updated without triggering a recalculation of <code>expensiveCalculation</code>, which optimizes performance.</p>
</li>
</ul>
<p>Now with the compiler in React 19, this is no longer required. You can just write your code and React will apply the memoziation.</p>
<p>Look at this code example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// No need for manual memoization React 19</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Component</span>(<span class="hljs-params">{ children }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p><strong>Code explanation:</strong> you no longer need to use <code>useCallback</code> or <code>useMemo</code> – React 19 automatically handles optimizations.</p>
<h2 id="heading-no-forwardref-simplified-ref-handling"><strong>No</strong> <code>forwardRef</code><strong>: Simplified Ref Handling</strong></h2>
<p>Using <code>forwardRef</code> to pass refs around used to be a bit of a chore. 😓 But in React 19, you can pass refs just like any other prop. This streamlines your component code and makes ref handling a breeze. 🧹</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Child</span>(<span class="hljs-params">{ innerRef }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{innerRef}</span> /&gt;</span></span>;
}
</code></pre>
<p><strong>Code explanation :</strong><code>forwardRef</code> is no longer required – instead, refs are passed like regular props.</p>
<h2 id="heading-the-new-use-hook-a-game-changer"><strong>The New</strong> <code>use()</code> Hook: A Game Changer</h2>
<p>The versatile new <code>use()</code> hook replaces multiple hooks, such as <code>useEffect</code> for data fetching as well as <code>useContext</code> and <code>useState</code> for consuming context data. It simplifies your code by handling promises and context with a single, elegant solution.</p>
<p>Look at this code example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> DataFetchingComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [data, setData] = useState(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">true</span>);
  <span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
        <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> response.json();
        setData(result);
      } <span class="hljs-keyword">catch</span> (err) {
        setError(err.message);
      } <span class="hljs-keyword">finally</span> {
        setLoading(<span class="hljs-literal">false</span>);
      }
    };

    fetchData();
  }, []);

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error: {error}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Data:<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">pre</span>&gt;</span>{JSON.stringify(data, null, 2)}<span class="hljs-tag">&lt;/<span class="hljs-name">pre</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> DataFetchingComponent;
</code></pre>
<p><strong>Code Explanation:</strong></p>
<ul>
<li><p><code>useEffect</code> is triggered after the component mounts to initiate data fetching.</p>
</li>
<li><p>We maintain <code>loading</code>, <code>data</code>, and <code>error</code> states to manage and display the appropriate UI.</p>
</li>
<li><p>Once the data is fetched, the state updates, triggering a re-render to display the data.</p>
</li>
</ul>
<p>Now with the help of the new <code>use()</code> hook in React 19, data fetching becomes easier and you don’t need to depend on state management hooks like <code>useState()</code> anymore.</p>
<p>Here is an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { use } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-comment">// Function to fetch data</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
  <span class="hljs-keyword">if</span> (!response.ok) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Failed to fetch data'</span>);
  }
  <span class="hljs-keyword">return</span> response.json();
}

<span class="hljs-keyword">const</span> DataFetchingComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// `use()` suspends the component until the promise resolves</span>
  <span class="hljs-keyword">const</span> data = use(fetchData());

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Data:<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">pre</span>&gt;</span>{JSON.stringify(data, null, 2)}<span class="hljs-tag">&lt;/<span class="hljs-name">pre</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> DataFetchingComponent;
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><strong>Suspense and</strong> <code>use()</code>: When you use <code>use()</code>, it suspends the component rendering until the promise resolves. If an error occurs, it can also trigger a <code>Suspense</code> error boundary.</p>
</li>
<li><p><strong>No need for</strong> <code>useEffect</code>: There's no need to manually manage data fetching with side effects, as React handles it under the hood.</p>
</li>
<li><p><strong>Error and loading states</strong>: These can now be managed globally using <code>Suspense</code> error boundaries without manually tracking states like <code>loading</code> or <code>error</code>.</p>
</li>
</ul>
<h3 id="heading-fetch-data-with-use-vs-useeffect"><strong>Fetch Data with</strong> <code>use()</code> vs. <code>useEffect</code></h3>
<p>Fetching data used to require a bit of boilerplate with <code>useEffect</code>. With <code>use()</code>, you just resolve the promise and use React Suspense for a clean, easy data-fetching experience. 🧼 This means less code and more focus on what matters.</p>
<h3 id="heading-use-context-with-use"><strong>Use Context with</strong> <code>use()</code></h3>
<p>Handling context data has also become more straightforward. The new <code>use()</code> hook can now consume context directly, eliminating the need for <code>useContext</code> and making context management more intuitive. 🎯</p>
<h2 id="heading-directives-a-fresh-approach"><strong>Directives: A Fresh Approach</strong></h2>
<p>If you’ve been using Next.js, you might have seen directives already. 🌐 React 19 introduces directives to simplify component configuration. Use <code>use client</code> for client-side components and <code>use server</code> for server-side ones. It’s as easy as adding a string at the top of your file:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"use client"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ClientComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Client Side<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p><strong>Code explanation:</strong> Use <code>use client</code> and <code>use server</code> to declare client-side or server-side components.</p>
<h2 id="heading-actions-streamlined-form-handling"><strong>Actions: Streamlined Form Handling</strong></h2>
<p>Forms just got a major upgrade with actions. 💥 Actions are functions connected to form submissions that can run on either the server or client side. This means cleaner code and a smoother form-handling process.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">action</span>(<span class="hljs-params">formData</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> handleSubmit(formData);
}
</code></pre>
<p><strong>Code explanation:</strong> Actions handle form submissions, running on the client or server.</p>
<h4 id="heading-client-actions-a-practical-example"><strong>Client Actions: A Practical Example</strong></h4>
<p>Client actions are great for immediate feedback. For example, alerting users with their input values has never been simpler. Just use <code>use client</code> and connect the form action to the form’s action prop. Easy peasy! 🥳</p>
<h2 id="heading-useformstatus-managing-form-state"><code>useFormStatus()</code>: Managing Form State</h2>
<p>Keep track of your form submissions with the <code>useFormStatus()</code> hook. 🕒 It helps manage form states like disabling the submit button while the form is pending. This is a must-have for smooth user experiences.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { pending } = useFormStatus();
<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{pending}</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
</code></pre>
<p><strong>Code explanation:</strong> <code>useFormStatus()</code> tracks form submission states, like disabling a button during submission.</p>
<h2 id="heading-useformstate-stateful-form-actions"><code>useFormState()</code>: Stateful Form Actions</h2>
<p>We now have <code>useFormState()</code>, which is a new hook for managing form state. 🎛️ It’s similar to <code>useState</code> but works with form actions, allowing you to access both previous state and submitted data. It’s perfect for scenarios like adding items to a cart.</p>
<p>I feel <code>useFormState()</code> is closely associated with the features in the React Hook Form library, as its working features are mostly similar.</p>
<p>Here is a code example to help you understand it better:</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> { useForm, useFormState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;

<span class="hljs-keyword">const</span> MyForm = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { register, handleSubmit, control } = useForm();
  <span class="hljs-keyword">const</span> { isSubmitting, isDirty, isValid } = useFormState({ control });

  <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit(onSubmit)}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"firstName"</span>&gt;</span>First Name:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> {<span class="hljs-attr">...register</span>('<span class="hljs-attr">firstName</span>', { <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span> })} /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"lastName"</span>&gt;</span>Last Name:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> {<span class="hljs-attr">...register</span>('<span class="hljs-attr">lastName</span>', { <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span> })} /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{isSubmitting</span> || !<span class="hljs-attr">isValid</span>}&gt;</span>
        Submit
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Form is {isDirty ? 'dirty' : 'pristine'}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Submitting: {isSubmitting ? 'Yes' : 'No'}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyForm;
</code></pre>
<p><strong>Code explanation:</strong></p>
<ol>
<li><p><strong>Import Hooks</strong>: We import <code>useForm</code> and <code>useFormState</code> from <code>react-hook-form</code>.</p>
</li>
<li><p><strong>Setup Form</strong>:</p>
<ul>
<li><p><code>useForm</code>: This hook initializes the form methods, including <code>register</code>, <code>handleSubmit</code>, and <code>control</code>.</p>
</li>
<li><p><code>useFormState</code>: We use this hook to extract form-state properties like <code>isSubmitting</code>, <code>isDirty</code>, and <code>isValid</code>.</p>
</li>
</ul>
</li>
<li><p><strong>Register Inputs</strong>: We register each input field using the <code>register</code> function, specifying any validation rules (for example <code>required</code>).</p>
</li>
<li><p><strong>Handle Submission</strong>: The <code>onSubmit</code> function handles the form submission, where you can perform your desired actions with the form data.</p>
</li>
<li><p><strong>Form State Info</strong>: We display the form's current state (whether it's dirty or submitted) below the form.</p>
</li>
</ol>
<h3 id="heading-key-features-of-useformstate">Key Features of <code>useFormState</code>:</h3>
<ul>
<li><p><strong>Performance</strong>: <code>useFormState</code> only re-renders when the specific fields it's monitoring change, making it efficient.</p>
</li>
<li><p><strong>Controlled State</strong>: You can easily manage and observe the form's state without writing boilerplate code for handling changes and validations.</p>
</li>
</ul>
<h2 id="heading-useoptimistic-enhancing-user-experience"><code>useOptimistic()</code>: Enhancing User Experience</h2>
<p>For real-time applications, the <code>useOptimistic()</code> hook is helpful. 💬 It allows for optimistic updates, making your app feel snappy by updating the UI instantly and syncing with the server in the background.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [optimisticState, setOptimistic] = useOptimistic(initialState);
</code></pre>
<p><strong>Code explanation:</strong> Enables optimistic UI updates before syncing with the server.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>React 19 is here to simplify your coding experience and enhance performance. 🎉 To dive deep into all these features and more, check out my recent <a target="_blank" href="https://www.freecodecamp.org/news/learn-react-hooks-with-example-code/">article</a> about React Hooks.</p>
<p>If you’re ready to streamline your React projects, embrace the future with React 19 and make your development experience smoother and more enjoyable. 🌟</p>
<ul>
<li><p>Follow Me on X: <a target="_blank" href="https://x.com/prankurpandeyy">Prankur's Twitter</a></p>
</li>
<li><p>Follow me on Linkedin: <a target="_blank" href="https://linkedin.com/in/prankurpandeyy">Prankur's Linkedin</a></p>
</li>
<li><p>Look at my Portfolio here: <a target="_blank" href="https://prankurpandeyy.netlify.app">Prankur's Portfolio</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <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>
