<?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" version="2.0"><channel><title><![CDATA[Chahat's blogs]]></title><description><![CDATA[A passionate frontend developer who loves to code in ReactJS and other modern frontend tools.]]></description><link>https://chahatbhatia.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 01 Sep 2026 02:27:23 GMT</lastBuildDate><atom:link href="https://chahatbhatia.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Mastering Intervals With React Hooks: Tips to Avoid Common Mistakes]]></title><description><![CDATA[In this article, we will dive into the world of intervals in React and how to leverage the power of hooks to handle them effectively. Whether you're a beginner or an experienced developer, understanding the nuances of intervals is crucial for buildin...]]></description><link>https://chahatbhatia.hashnode.dev/mastering-intervals-with-react-hooks</link><guid isPermaLink="true">https://chahatbhatia.hashnode.dev/mastering-intervals-with-react-hooks</guid><category><![CDATA[React]]></category><category><![CDATA[ReactHooks]]></category><category><![CDATA[useEffect]]></category><category><![CDATA[setInterval]]></category><category><![CDATA[useState]]></category><dc:creator><![CDATA[Chahat Bhatia]]></dc:creator><pubDate>Sun, 16 Jul 2023 05:12:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1689447186179/80e6a8be-7e02-4616-9e84-390057514201.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we will dive into the world of intervals in React and how to leverage the power of hooks to handle them effectively. Whether you're a beginner or an experienced developer, understanding the nuances of intervals is crucial for building efficient and error-free applications. Let's explore some best practices to use intervals in React hooks while steering clear of common pitfalls and optimizing your projects for better performance.</p>
<p>Let’s look at a naive implementation of a counter that increments a number every second using <code>setInterval</code>:</p>
<h6 id="heading-this-code-does-not-work"><strong>This code does not work.</strong></h6>
<pre><code class="lang-javascript"><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">Counter</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
            setCount(count + <span class="hljs-number">1</span>);
        }, <span class="hljs-number">1000</span>);
    }, []);

    <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">"App"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>The current count is:<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{count}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}
</code></pre>
<p>To understand why this code does not work, you have to understand how React deals with the state. Dan Abramov <a target="_blank" href="https://overreacted.io/a-complete-guide-to-useeffect/">wrote a fantastic (and very long)</a> guide to explain this.</p>
<p>In short, using <code>setCount(count + 1)</code> we are directly referencing the <code>count</code> variable from the current scope. However, in the context of <code>setInterval</code> callback, the <code>count</code> variable gets captured inside the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures"><strong>CLOSURE</strong></a> during the Initial Render of the component. This means that the subsequent <code>setCount</code> calls will always use the stale values of the <code>count</code> variable.</p>
<p>As a result, the first time the component is rendered:</p>
<ol>
<li><p>The count variable is set to 0 (initial state).</p>
</li>
<li><p>After the component is rendered and painted, React will execute the <code>useEffect</code>hook. The <code>useEffect</code> hook will register the interval. The registered interval has access to the <code>count</code> variable (which is 0).</p>
</li>
<li><p>After 1 second the callback will be invoked. It will call <code>setCount(0 + 1)</code>. This will</p>
<p> trigger a re-render of the component with the state <code>count</code> value as 1.</p>
</li>
</ol>
<p>The second time the component is rendered:</p>
<ol>
<li><p>The count variable is set to 1.</p>
</li>
<li><p>The updated value of <code>count</code> gets painted on the screen.</p>
</li>
<li><p>The <code>useEffect</code> does not run since the empty dependency array <code>[]</code> defines that the hook should only run on the first render.</p>
</li>
<li><p>After 1 second the callback function gets called again but this time instead of taking count value as 1, it again takes <code>count</code> as 0. This is because of the closure associated with the <code>setInterval</code> callback function.</p>
</li>
<li><p>The <code>setCount</code> method again tries to set the value of count as <code>0 + 1</code> i.e. <code>1</code> which is already set in the current state so React will not trigger the re-render again since the state never gets updated (All credit goes to <a target="_blank" href="https://chahatbhatia.hashnode.dev/exploring-react-fiber-architecture">React Fiber</a> Diffing algorithm).</p>
</li>
</ol>
<h2 id="heading-solving-the-state-problem"><strong># Solving the state problem</strong></h2>
<h3 id="heading-solution-1-rebuild-the-effect-on-every-render"><strong>Solution 1: Rebuild the effect on every render</strong></h3>
<p>Adding the <code>count</code> variable in the dependency array lets our <code>useEffect</code> to run on each state update.</p>
<p>In this case each time the <code>setCount</code> is called, React will call the cleanup function (unmounts the component) before calling the useEffect again. This will call the <code>clearInterval</code> function to clear the current interval and in the subsequent effect calls registers a new <code>setInterval</code> which gets the updated value of the <code>count</code> variable.</p>
<p>Here is the code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</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">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> interval = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
      setCount(count + <span class="hljs-number">1</span>);
    }, <span class="hljs-number">1000</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">clearInterval</span>(interval)
  }, [count]);

  <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">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>The current count is:<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{count}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p><strong>Cons</strong>: The Component is unmounting and mounting again and again.</p>
<h3 id="heading-solution-2-using-a-callback-function-in-setcount"><strong>Solution 2: Using a callback function in</strong> <code>setCount()</code></h3>
<p>Using a callback function <code>(prevCount) =&gt; prevCount + 1)</code> in <code>setCount</code>, React guarantees that the value passed to the state update function is the latest state value at the time of the update. React internally handles this and is able to achieve this by scheduling state updates and batching them together.</p>
<p>By using the functional form of <code>setCount</code>, you can safely update the state based on its previous value and avoid potential bugs or incorrect state updates.</p>
<p>And using an empty dependency array <code>[]</code> ensures that the subsequent unmounting and mounting is prevented which was the bad thing in the previous solution.</p>
<p>Here is the code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</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">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
      setCount(<span class="hljs-function">(<span class="hljs-params">prevCount</span>) =&gt;</span> prevCount + <span class="hljs-number">1</span>);
    }, <span class="hljs-number">1000</span>);
  }, []);

  <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">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>The current count is:<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{count}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-solution-3-using-the-usereducer-hook"><strong>Solution 3: Using the</strong> <code>useReducer</code> <strong>hook</strong></h3>
<p>React deals with the state issue with one more efficient solution which is to use the <code>useReducer</code> hook. The default behavior of the dispatch function is to access the most current state of the component. Dispatch will let you access the “future” state.</p>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Very flexible solution</p>
</li>
<li><p>Follows React design patterns</p>
</li>
</ul>
<p>Here is the code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useEffect, useReducer } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> reducer = <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"Increment"</span>:
      <span class="hljs-keyword">return</span> state + <span class="hljs-number">1</span>;
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
}

<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">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, dispatch] = useReducer(reducer, <span class="hljs-number">0</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
      dispatch({<span class="hljs-attr">type</span>: <span class="hljs-string">"Increment"</span>});
    }, <span class="hljs-number">1000</span>);
  }, []);

  <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">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>The current count is:<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{count}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-conclusion"><strong>Conclusion 🤙🏽</strong></h2>
<p>I hope this article will help you in gaining confidence when working with intervals and timeouts in React. Let me know if this article helped you by leaving a comment and a clap. Follow me for more informative and insightful articles in the future : ).</p>
]]></content:encoded></item><item><title><![CDATA[Exploring React Fiber Architecture: Empowering Efficient User Interfaces]]></title><description><![CDATA[Introduction:
React Fiber, a reimplementation of the React core algorithm, is revolutionizing the performance and efficiency of user interfaces. By introducing a new rendering engine, React Fiber has made significant strides in scheduling, concurrenc...]]></description><link>https://chahatbhatia.hashnode.dev/exploring-react-fiber-architecture</link><guid isPermaLink="true">https://chahatbhatia.hashnode.dev/exploring-react-fiber-architecture</guid><category><![CDATA[React]]></category><category><![CDATA[React Fiber]]></category><category><![CDATA[reconcilliation]]></category><category><![CDATA[virtual dom]]></category><dc:creator><![CDATA[Chahat Bhatia]]></dc:creator><pubDate>Wed, 12 Jul 2023 12:14:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1689146786234/2295590b-e2ef-4a5c-a6d4-e2e2bf453913.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction"><strong>Introduction</strong>:</h3>
<p>React Fiber, a reimplementation of the React core algorithm, is revolutionizing the performance and efficiency of user interfaces. By introducing a new rendering engine, React Fiber has made significant strides in scheduling, concurrency, and rendering capabilities. In this blog post, we will dive into the details of React Fiber architecture, exploring its key concepts and benefits.</p>
<h3 id="heading-fiber-design-philosophy"><strong>Fiber Design Philosophy</strong></h3>
<p><a target="_blank" href="https://github.com/acdlite/react-fiber-architecture">Fiber</a> is the refactoring of the React core algorithm, which took more than two years of effort from the Facebook Team. Fiber architecture was introduced in React v16.0, and some of the design philosophies are worth learning. We will get to that but first, let's see how frames play an important role in updating the UI.</p>
<p><strong>• How do Browsers render the UI using frames?</strong></p>
<p>For a browser, the pages are made frame by frame, and the frame rendering rate is consistent with the refresh rate of the device. In general, the screen refresh rate is 60 times per second, and the page is rendered smoothly when the frames per second (FPS) exceed 60. Otherwise, the page may get frozen. The following figure shows what happens in a complete frame:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689165000433/015250cc-9dea-4d12-81d2-735d92fc4e7b.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>First, process the input event to give users feedback as soon as possible.</p>
</li>
<li><p>Second, check the timers to see if they have reached the scheduled time and perform the corresponding callback at the same time.</p>
</li>
<li><p>Third, check the Begin Frame (events of each frame), including <code>window.resize</code>, scroll, media query change, etc.</p>
</li>
<li><p>Fourth, execute the <code>requestAnimationFrame (rAF)</code>. Before painting, rAF callback is executed.</p>
</li>
<li><p>Fifth, perform Layout operation, including layout calculation and update, namely how an element is styled and displayed on the page.</p>
</li>
<li><p>Sixth, Perform Paint operation. The size and position of each node in the tree are obtained, and the content of each element is filled by the browser.</p>
</li>
<li><p>Now, the browser enters an idle period. Execute the tasks registered in <code>requestIdleCallback</code>. <code>requestIdleCallback</code> forms the foundation of React Fiber, but we’ll get back to it later.</p>
</li>
</ol>
<p>The JS engine and the page rendering engine work in the same rendering thread in a mutually exclusive manner. If the task executed at a certain stage is very time-consuming (for example, the Timers or Begin Frame stage takes longer than 16ms), the page rendering will be interrupted, leading to page stuttering.</p>
<p><strong>• How Reconciliation used to work before Fiber?</strong></p>
<p>Before the Fiber architecture was introduced, React would compare the virtual DOM tree recursively to find the nodes that need to be changed and update them synchronously. In this process, which was called <strong>reconciliation</strong>, React would keep consuming browser resources, so the browser might fail to respond to user-triggered events.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689165041131/fd8c93cb-f3f3-4d7f-9068-91bba8d06979.png" alt class="image--center mx-auto" /></p>
<p>The traversal is a recursive call, which leads to a deeper execution stack that cannot be interrupted. Otherwise, it cannot be recovered. If the recursion goes very deep, the browser stutters. If the recursion takes 100ms, the browser cannot respond to user actions during this period.</p>
<p>To address these issues, <strong><em>Fiber</em></strong> is introduced to split the rendering and updating process into small tasks (units of work). These are executed as per an appropriate scheduling mechanism to specify the timing for task execution to reduce stuttering and improve the page interaction experience.</p>
<h3 id="heading-react-fiber-the-game-changer"><strong>React Fiber: The Game Changer</strong></h3>
<p>In a nutshell, React Fiber is simply a reimplementation of React’s core reconciliation algorithm. It can be said to be the reimplementation of the stack but specialized for react components(where the stack can be interrupted at will and stack frames manipulated manually). It has been the default reconciler since React 16.</p>
<p>The primary goal of the React Fiber reconciliation algorithm is to enable React to take advantage of scheduling(which was not possible with the previous stack reconciler). React is now able to:</p>
<ul>
<li><p>pause work and come back to it later.</p>
</li>
<li><p>split work into chunks and prioritize tasks</p>
</li>
<li><p>to reuse previously completed work.</p>
</li>
<li><p>abort work if it’s no longer needed.</p>
</li>
</ul>
<p>As a result, there is an overall improvement in the responsiveness of the UI and overall performance of React applications, especially apps with animations.</p>
<p><strong>⇒ Structure of a Fiber</strong></p>
<p>Fiber is also considered as a data structure, and React Fiber is implemented in a linked list. Each Virtual DOM can be taken as a fiber. As shown in the following figure, each node is a fiber, including attributes such as child (the first child node), sibling (sibling nodes), and return (the parent nodes).</p>
<p><img src="https://yqintl.alicdn.com/f49c9f904ccf9c9da2022df52dac985da2028488.png" alt /></p>
<h2 id="heading-how-react-fiber-works"><strong>How React Fiber Works?</strong></h2>
<p>Since a fiber presents a unit of work, before React renders anything to the DOM, it processes each fiber(unit of work) until we end up with something called ‘finished work’. React then commits this ‘finished work’ which results in visible changes in the DOM. This all happens in two phases.</p>
<p><strong>• Rendering a tree of fibers</strong></p>
<p>There are two trees Fiber uses to render our UI, the <strong><em>current</em></strong> and <strong><em>workinProgress</em></strong> tree. The current tree is what is currently rendered on the UI(or Screen); React can’t make changes to this tree because it will result in an inconsistent UI. React instead makes changes to the workinProgress tree and swaps pointers once all changes are computed. The current tree then becomes the workinProgress tree, and the workinProgress tree becomes the current tree.</p>
<p><img src="https://blog.openreplay.com/images/react-fiber-explained/images/image03.png" alt="3" /></p>
<p>How does Fiber avoid UI inconsistency? By simply splitting work into two phases:</p>
<h3 id="heading-1-renderreconciliation-phase"><strong>1. Render/Reconciliation Phase</strong></h3>
<p>In this phase, React starts building the workinProgress tree, which follows a process like this:</p>
<ul>
<li><p><code>setState()</code> method is called to update a component’s state React knows it has to now schedule the work using <code>requestIdleCallback()</code>, which lets the main thread know that it has to pick up the work once it has some free(Idle) time.</p>
</li>
<li><p>React now starts creating the workinProgress Fiber tree by cloning the elements from the current Fiber tree and goes through each node to determine if it has to be changed</p>
</li>
<li><p>If a particular node has been updated, it is added to another list called an effects list, a linear linked list of all the changes that need to be made.</p>
</li>
<li><p>Once the entire workinProgress tree is traversed, and all the updated nodes are tagged, the first phase is completed.</p>
</li>
</ul>
<h3 id="heading-2-commit-phase"><strong>2. Commit Phase</strong></h3>
<p>In this phase, all the updates for the nodes in the effect list are performed and reflected on the DOM. The main thread applies all these changes in a single go. This phase is synchronous, unlike the render phase, which can be paused and resumed.</p>
<h2 id="heading-react-fiber-benefits"><strong>React Fiber Benefits</strong></h2>
<p>Some features that you can currently use in React because of Fiber are:</p>
<ul>
<li><p><a target="_blank" href="https://github.com/bvaughn/react-error-boundary">Error boundaries</a>—previously, when errors happen in the <code>render</code> method, it messes React up internally. But with error boundaries, we can prevent this from happening. This is done through the <code>getDerivedStateFromError()</code> and <code>componentDidCatch()</code> methods.</p>
</li>
<li><p><a target="_blank" href="https://reactjs.org/docs/code-splitting.html">Code-splitting</a> and Concurrency(thanks to React 18).</p>
</li>
</ul>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>This article is a simple introduction to the React Fiber algorithm and a high-level view of how it works. There is a deeper level of abstraction to the algorithm, but you now know the fundamental concepts behind the Fiber Reconciler and how it works.</p>
<h3 id="heading-additional-resources"><strong>Additional Resources</strong></h3>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=ZCuYPiUIONs&amp;t=1663s">Watch</a> Lin Clark - A Cartoon Intro to Fiber - React Conf 2017</p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=bvFpe5j9-zQ&amp;list=PLb0IAmt7-GS0kj3saZuh4vzfldxEdH5RH&amp;index=3">Watch</a> Sebastian Markbåge - React Performance End to End (React Fiber)— React Conf 2017</p>
</li>
<li><p><a target="_blank" href="https://reactjs.org/docs/faq-internals.html">Read</a> React-fiber-architecture— React Docs</p>
</li>
</ul>
]]></content:encoded></item></channel></rss>