<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rakeshraj on Medium]]></title>
        <description><![CDATA[Stories by Rakeshraj on Medium]]></description>
        <link>https://medium.com/@rakeshraj2097?source=rss-263365aced87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bGUzNjzjm9VUjksl</url>
            <title>Stories by Rakeshraj on Medium</title>
            <link>https://medium.com/@rakeshraj2097?source=rss-263365aced87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:40:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rakeshraj2097/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How setTimeout Works Inside the JavaScript Event Loop and Task Queue]]></title>
            <link>https://medium.com/@rakeshraj2097/how-settimeout-works-inside-the-javascript-event-loop-and-task-queue-d3b6c4bf6a02?source=rss-263365aced87------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3b6c4bf6a02</guid>
            <dc:creator><![CDATA[Rakeshraj]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 22:38:22 GMT</pubDate>
            <atom:updated>2025-09-17T22:38:22.431Z</atom:updated>
            <content:encoded><![CDATA[<p>When you write:</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Hello, World!&quot;);<br>}, 1000);</pre><p>You probably expect it to run “after 1000ms.”<br> But the deeper question is: <strong>when does the callback actually enter the task queue, and what happens if the main thread is idle before that?</strong></p><p>Let’s break it down step by step.</p><h3>1. The Components of Asynchronous JavaScript</h3><p>Before diving into setTimeout, let’s recall the main players:</p><ul><li><strong>Call Stack</strong> → executes synchronous code.</li><li><strong>Web APIs</strong> → environment features like timers, fetch, DOM events.</li><li><strong>Task Queue (Macrotask Queue)</strong> → holds callbacks from setTimeout, setInterval, etc.</li><li><strong>Microtask Queue</strong> → holds callbacks from Promises and queueMicrotask.</li><li><strong>Event Loop</strong> → continuously checks if the stack is empty and moves queued tasks into it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRbGq0g700WpBo7OiSf-uw.png" /></figure><h3>2. Registering a Timer with setTimeout</h3><p>At <strong>t=0ms</strong>, when the JS engine encounters:</p><pre>setTimeout(callback, 1000);</pre><ul><li>The callback is <strong>not added to the task queue immediately</strong>.</li><li>Instead, the Web APIs start a <strong>1000ms timer</strong> in the background.</li><li>The callback is stored there until the timer completes.</li></ul><h3>3. Waiting Phase: Main Thread Idle vs. Timer Running</h3><p>Suppose the call stack is already empty at <strong>100ms</strong>.</p><p>Does the callback run early? ❌</p><ul><li>No. The callback is still sitting inside Web APIs, waiting for the timer.</li><li>From <strong>100ms → 1000ms</strong>, even if the main thread is idle, the callback does nothing.</li></ul><p>👉 setTimeout always enforces a <strong>minimum delay</strong>.</p><h3>4. Timer Expiry and Callback Queueing</h3><p>At <strong>≈1000ms</strong>:</p><ul><li>The Web APIs move the callback into the <strong>Task Queue</strong>.</li><li>The Event Loop checks:</li><li>Is the call stack empty?</li><li>Are there microtasks waiting?</li><li>If yes → it moves the callback into the call stack and executes it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sTysWfaRTUFOzdngtojZw.png" /></figure><h3>5. Blocking the Event Loop</h3><p>What if the main thread is blocked?</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Timer fired!&quot;);<br>}, 1000);</pre><pre>const start = Date.now();<br>while (Date.now() &lt; start + 2000) {} // blocks ~2s</pre><p>Here’s what happens:</p><ul><li>Timer finishes at 1000ms.</li><li>But the main thread is busy until 2000ms.</li><li>The callback executes <strong>only after 2000ms</strong>, not at 1000ms.</li></ul><p>👉 Proves that setTimeout is “at least this much delay,” not exact scheduling.</p><h3>6. The Special Case of setTimeout(fn, 0)</h3><p>Even with zero delay:</p><pre>setTimeout(() =&gt; console.log(&quot;Zero!&quot;), 0);</pre><p>It still:</p><ol><li>Goes to Web APIs.</li><li>Waits for the 0ms timer.</li><li>Moves into the <strong>Task Queue</strong>.</li><li>Runs only <strong>after microtasks</strong> (like Promise.resolve().then) finish.</li></ol><p>That’s why microtasks have higher priority than macrotasks</p><h3>Conclusion: The Real Behavior of setTimeout</h3><p>To summarize:</p><ul><li>At scheduling time → the callback goes to Web APIs, not the queue.</li><li>During the delay → callback waits in Web APIs, even if the thread is idle.</li><li>At timer expiry → callback moves to the Task Queue.</li><li>The Event Loop executes it only when the stack is free (after microtasks).</li><li>Blocking code can delay execution far beyond the timer.</li></ul><p>So setTimeout isn’t a stopwatch. It’s more like setting an alarm:<br> 👉 <em>“Not before this time, and only when the stage is clear.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3b6c4bf6a02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Normalizing My React State Fixed a Ton of Repetition and Bugs.]]></title>
            <link>https://medium.com/@rakeshraj2097/how-normalizing-my-react-state-fixed-a-ton-of-repetition-and-bugs-22751c2d5b8a?source=rss-263365aced87------2</link>
            <guid isPermaLink="false">https://medium.com/p/22751c2d5b8a</guid>
            <dc:creator><![CDATA[Rakeshraj]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 07:10:13 GMT</pubDate>
            <atom:updated>2025-07-05T07:11:36.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOWuiVwwug2_iA4KwGHoSQ.jpeg" /></figure><p>A while ago, I was building a blog app in React.<br>Each blog post had a title and an author. Naturally, I fetched all the posts and stored them directly in state.</p><p>Everything looked great. The UI was rendering as expected, and development was moving smoothly — until a simple request came in:</p><blockquote><em>“Hey, can you update the author name from </em>Alice<em> to </em>Alicia<em>? It should reflect in all posts.”</em></blockquote><p>Seemed like a quick fix. I opened the code, expecting a one-line change.</p><p>Instead, I saw this:</p><pre>const [posts, setPosts] = useState([<br>  {<br>    id: 1,<br>    title: &quot;React Basics&quot;,<br>    author: { id: 101, name: &quot;Alice&quot; }<br>  },<br>  {<br>    id: 2,<br>    title: &quot;Advanced Redux&quot;,<br>    author: { id: 101, name: &quot;Alice&quot; }<br>  }<br>]);</pre><p>Alice’s details were duplicated across multiple posts. To update her name, I had to loop through every post and replace her manually.</p><pre>setPosts(prev =&gt;<br>  prev.map(post =&gt;<br>    post.author.id === 101<br>      ? { ...post, author: { ...post.author, name: &quot;Alicia&quot; } }<br>      : post<br>  )<br>);</pre><p>It worked — but it felt wrong.</p><p>What if Alice appeared in <strong>comments</strong>, <strong>likes</strong>, or <strong>messages</strong> too?<br>Would I have to update her name in <strong>every place</strong> she’s used?</p><p>That’s when it hit me:</p><blockquote><em>I was storing the same piece of data in too many places.</em></blockquote><p>So I took a step back and asked myself:</p><p><strong>How do databases solve this problem?</strong></p><p>They normalize data.</p><p>Meaning:</p><ul><li>Instead of repeating the same author object in every post,</li><li>You store the author data once and reference it by ID.</li></ul><p>I refactored my state.</p><p>Instead of this nested structure, I flattened the data:</p><pre>const [posts, setPosts] = useState({<br>  byId: {<br>    1: { id: 1, title: &quot;React Basics&quot;, authorId: 101 },<br>    2: { id: 2, title: &quot;Advanced Redux&quot;, authorId: 101 }<br>  },<br>  allIds: [1, 2]<br>});<br>const [authors, setAuthors] = useState({<br>  byId: {<br>    101: { id: 101, name: &quot;Alice&quot; }<br>  },<br>  allIds: [101]<br>});</pre><p>Now, when I needed to update Alice’s name, it became as simple as:</p><pre>setAuthors(prev =&gt; ({<br>  ...prev,<br>  byId: {<br>    ...prev.byId,<br>    101: { ...prev.byId[101], name: &quot;Alicia&quot; }<br>  }<br>}));</pre><p>No more looping through posts.<br> No more duplicated updates.</p><p>Displaying the data was just as clean:</p><pre>{posts.allIds.map(id =&gt; {<br>  const post = posts.byId[id];<br>  const author = authors.byId[post.authorId];<br>  return (<br>    &lt;div key={post.id}&gt;<br>      &lt;h3&gt;{post.title}&lt;/h3&gt;<br>      &lt;p&gt;Author: {author.name}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>})}</pre><p>Each post still shows the correct author, and now I only have one place to update that author’s details.</p><p>If you’re new to React, here’s why this <strong>normalization pattern</strong> is so useful:</p><p>✅ <strong>No duplication</strong> — your data stays clean and DRY<br> ✅ <strong>Easy updates</strong> — change it once, reflect it everywhere<br> ✅ <strong>Scales well</strong> — works beautifully for large apps with shared data</p><p>You don’t need any external libraries. This is just plain JavaScript with a thoughtful data structure. Treat your frontend state like a mini database:</p><ul><li>Posts reference authors by ID</li><li>Comments reference users by ID</li><li>Products reference categories by ID</li></ul><p>To be clear: If you’re building a small app, this might feel like overkill.</p><p>But once your app grows — and users, authors, products, or any entities appear in multiple places — normalized state becomes a lifesaver.</p><p>I learned it the hard way. Now I use it by default.</p><p><strong>Thanks for reading!</strong><br>If you found this useful or learned something new, feel free to share or leave your thoughts in the comments — I’d love to hear how others are managing their state in React!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22751c2d5b8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside the Event Loop: How JavaScript Really Works]]></title>
            <link>https://medium.com/@rakeshraj2097/javascripts-event-loop-the-mind-behind-the-magic-4a56608abab7?source=rss-263365aced87------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a56608abab7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[event-loop-in-javascript]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[node-js-development]]></category>
            <dc:creator><![CDATA[Rakeshraj]]></dc:creator>
            <pubDate>Wed, 07 May 2025 17:56:24 GMT</pubDate>
            <atom:updated>2025-05-08T06:13:16.791Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript is a single-threaded language, meaning it executes one piece of code at a time. However, through its powerful concurrency model based on the <strong>event loop</strong>, JavaScript handles asynchronous operations like I/O tasks, timers, and promises without blocking the main thread.</p><h3>1. What is the Event Loop?</h3><p>The <strong>event loop</strong> is the mechanism that enables JavaScript to perform non-blocking I/O operations, even though it has a single-threaded execution model. It does this by delegating tasks to the browser or Node.js APIs and handling the execution of callback functions via task queues.</p><h3>2. Task Queues: Macrotask vs Microtask</h3><h3>Macrotask Queue (Task Queue)</h3><p>Tasks include:</p><ul><li>setTimeout</li><li>setInterval</li><li>setImmediate (Node.js)</li><li>I/O events</li><li>UI rendering</li></ul><p>Only one macrotask is processed at a time. After it finishes, all available microtasks are processed before picking the next macrotask.</p><h3>Microtask Queue</h3><p>Microtasks include:</p><ul><li>Promise.then, .catch, .finally</li><li>queueMicrotask</li><li>MutationObserver</li></ul><p><strong>Microtasks have a higher priority than macrotasks.</strong> After executing a macrotask, the event loop processes <strong>all</strong> queued microtasks before the next macrotask.</p><h3>3. Event Loop Execution Flow</h3><ol><li>Execute synchronous code (global execution context).</li><li>Process <strong>all microtasks</strong>.</li><li>Execute one <strong>macrotask</strong> from the queue.</li><li>Repeat steps 2–3.</li></ol><h3><strong>4. Visual Diagram of the Event Loop</strong></h3><p>This diagram illustrates how the event loop alternates between handling macrotasks and microtasks, prioritizing microtasks after each macrotask execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Y8ihwo4cltDGmBz-kJoVwQ.jpeg" /></figure><h3>5. Code Examples</h3><h3>📌 Basic Microtask vs Macrotask</h3><pre>console.log(&quot;Start&quot;);<br>setTimeout(() =&gt; {<br>  console.log(&quot;Macrotask - setTimeout&quot;);<br>}, 0);<br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Microtask - Promise&quot;);<br>});<br>console.log(&quot;End&quot;);</pre><p><strong>Output:</strong></p><pre>Start<br>End<br>Microtask - Promise<br>Macrotask - setTimeout</pre><h3>📌 Nested Microtasks</h3><pre>console.log(&quot;script start&quot;);<br>setTimeout(() =&gt; {<br>  console.log(&quot;setTimeout&quot;);<br>}, 0);<br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise 1&quot;);<br>  return Promise.resolve();<br>}).then(() =&gt; {<br>  console.log(&quot;promise 2&quot;);<br>});<br>console.log(&quot;script end&quot;);</pre><p><strong>Output:</strong></p><pre>script start<br>script end<br>promise 1<br>promise 2<br>setTimeout</pre><h3>📌 Node.js Specific: process.nextTick()</h3><pre>console.log(&quot;Start&quot;);<br>process.nextTick(() =&gt; console.log(&quot;nextTick&quot;));<br>Promise.resolve().then(() =&gt; console.log(&quot;promise&quot;));<br>setTimeout(() =&gt; console.log(&quot;timeout&quot;), 0);<br>console.log(&quot;End&quot;);</pre><p><strong>Output:</strong></p><pre>Start<br>End<br>nextTick<br>promise<br>timeout</pre><h3>6. How Does the Event Loop Decide What to Run?</h3><h3>🔁 Internal Event Loop Mechanics (Simplified)</h3><pre>while (true) {<br>  while (microtaskQueue.hasTasks()) {<br>    microtaskQueue.runNext();<br>  }<br>  const nextMacrotask = macrotaskQueue.getNext();<br>  nextMacrotask.run();<br>}</pre><h3>🧠 Internal Prioritization</h3><ul><li><strong>Synchronous Code:</strong> Executes first.</li><li><strong>Microtasks:</strong> Then microtasks like Promises or queueMicrotask() are executed in FIFO order.</li><li><strong>Macrotasks:</strong> Only after all microtasks finish, one macrotask is executed.</li><li><strong>Node.js Special Case:</strong> process.nextTick() runs before regular microtasks.</li></ul><h3>7. Summary</h3><ul><li>JavaScript uses an event loop to enable asynchronous programming.</li><li>Microtasks are prioritized over macrotasks.</li><li>Promises and queueMicrotask callbacks run immediately after the synchronous stack clears.</li><li>In Node.js, process.nextTick() has even higher priority than Promises.</li></ul><p>Understanding this flow helps in writing more efficient and predictable asynchronous JavaScript code.</p><h3>📚 Further Reading</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop">MDN Web Docs: Event Loop</a></li><li><a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/">Node.js Event Loop Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a56608abab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Higher-Order Component (HOC) Pattern in React]]></title>
            <link>https://medium.com/@rakeshraj2097/understanding-the-higher-order-component-hoc-pattern-in-react-a6649ce80bde?source=rss-263365aced87------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6649ce80bde</guid>
            <dc:creator><![CDATA[Rakeshraj]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 13:48:12 GMT</pubDate>
            <atom:updated>2025-01-16T13:48:12.556Z</atom:updated>
            <content:encoded><![CDATA[<p>In React, a Higher-Order Component (HOC) is an advanced technique for reusing component logic. An HOC is a function that takes a component and returns a new component. It allows you to share common functionality across multiple components while keeping them decoupled.</p><p>This article will explore the HOC pattern with an example that demonstrates incrementing a value in two different ways: on click and on hover.</p><h4>What is an HOC?</h4><p>An HOC is simply a JavaScript function:</p><pre>const withHOC = (WrappedComponent) =&gt; {<br>  return (props) =&gt; &lt;WrappedComponent {...props} /&gt;;<br>};</pre><p>It’s important to note that an HOC does not modify the original component. Instead, it creates a wrapper component that adds the desired behavior.</p><h4>Step 1: Separate Components</h4><p>Let’s start with two separate components that handle incrementing a count in different ways.</p><p><strong>ClickCounter Component:</strong></p><pre>import React, { useState } from &#39;react&#39;;<br><br>const ClickCounter = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  const increment = () =&gt; {<br>    setCount((prevCount) =&gt; prevCount + 1);<br>  };<br>  return &lt;button onClick={increment}&gt;Clicked {count} times&lt;/button&gt;;<br>};<br>export default ClickCounter;</pre><p><strong>HoverCounter Component:</strong></p><pre>import React, { useState } from &#39;react&#39;;<br><br>const HoverCounter = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  const increment = () =&gt; {<br>    setCount((prevCount) =&gt; prevCount + 1);<br>  };<br>  return &lt;p onMouseEnter={increment}&gt;Hovered {count} times&lt;/p&gt;;<br>};<br>export default HoverCounter;</pre><p>Both components have similar logic but implemented separately. This redundancy can be removed by using an HOC.</p><h4>Step 2: Create the Base HOC</h4><p>We’ll now define an HOC that extracts the shared logic.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const withIncrement = (WrappedComponent) =&gt; {<br>  return (props) =&gt; {<br>    const [count, setCount] = useState(0);<br>    const increment = () =&gt; {<br>      setCount((prevCount) =&gt; prevCount + 1);<br>    };<br>    return &lt;WrappedComponent count={count} increment={increment} {...props} /&gt;;<br>  };<br>};<br>export default withIncrement;</pre><p>In this HOC:</p><ul><li>The count state is managed in the HOC, and the WrappedComponent receives the current count and the increment function as props.</li></ul><h4>Step 3: Refactor Components to Use the HOC</h4><p>We’ll now refactor the ClickCounter and HoverCounter components to use the HOC.</p><p><strong>ClickCounterWithIncrement:</strong></p><pre>import React from &#39;react&#39;;<br>import withIncrement from &#39;./withIncrement&#39;;<br><br>const ClickCounter = ({ count, increment }) =&gt; {<br>  return &lt;button onClick={increment}&gt;Clicked {count} times&lt;/button&gt;;<br>};<br>export default withIncrement(ClickCounter);</pre><p><strong>HoverCounterWithIncrement:</strong></p><pre>import React from &#39;react&#39;;<br>import withIncrement from &#39;./withIncrement&#39;;<br><br>const HoverCounter = ({ count, increment }) =&gt; {<br>  return &lt;p onMouseEnter={increment}&gt;Hovered {count} times&lt;/p&gt;;<br>};<br>export default withIncrement(HoverCounter);</pre><h4>Step 4: Use the Enhanced Components</h4><p>Finally, render the enhanced components in your app:</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import ClickCounterWithIncrement from &#39;./ClickCounterWithIncrement&#39;;<br>import HoverCounterWithIncrement from &#39;./HoverCounterWithIncrement&#39;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Higher-Order Components Example&lt;/h1&gt;<br>      &lt;ClickCounterWithIncrement /&gt;<br>      &lt;HoverCounterWithIncrement /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));</pre><h3>Key Takeaways</h3><ol><li><strong>Reusability</strong>: HOCs allow you to encapsulate reusable logic and share it across multiple components.</li><li><strong>Separation of Concerns</strong>: Logic and UI remain decoupled, making your codebase more maintainable.</li><li><strong>Flexibility</strong>: You can customize HOCs by passing different configurations or behaviors.</li></ol><p>Using the HOC pattern effectively can lead to cleaner, more scalable React applications. However, with the advent of hooks, HOCs are sometimes replaced by custom hooks, but they still hold value in specific use cases.</p><h3>Credits</h3><p>This guide was inspired by the React documentation and written with the assistance of ChatGPT. For more details on Higher-Order Components, visit the <a href="https://reactjs.org/docs/higher-order-components.html">official React documentation</a>.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6649ce80bde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Best Way to Write a Reusable Table Component in React: From Props to Render Props]]></title>
            <link>https://medium.com/@rakeshraj2097/the-best-way-to-write-a-reusable-table-component-in-react-from-props-to-render-props-775f0812c136?source=rss-263365aced87------2</link>
            <guid isPermaLink="false">https://medium.com/p/775f0812c136</guid>
            <dc:creator><![CDATA[Rakeshraj]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 11:02:24 GMT</pubDate>
            <atom:updated>2024-10-20T11:02:24.870Z</atom:updated>
            <content:encoded><![CDATA[<p>When building a table component in React, you might start by passing props for static headers and rendering descriptions conditionally inside the component. While this works, the code can quickly become cluttered and difficult to extend. By introducing <strong>render props</strong>, we can achieve cleaner, more flexible code that scales with the needs of your application.</p><p>Let’s first look at how to build a table using normal props rendering and then refactor it using the render props pattern to demonstrate why it’s a better approach.</p><h3>Step 1: Normal Props Rendering in CommonTable</h3><p>Initially, you might write your table component with conditions for rendering descriptions based on specific props. Here’s how the CommonTable component might look using normal prop rendering:</p><pre>const staticHeaders = [<br>  { id: &#39;name&#39;, label: &#39;Name&#39; },<br>  { id: &#39;age&#39;, label: &#39;Age&#39; },<br>  { id: &#39;location&#39;, label: &#39;Location&#39; },<br>  { id: &#39;action&#39;, label: &#39;Action&#39; },<br>  { id: &#39;options&#39;, label: &#39;Options&#39; },<br>];<br><br>const CommonTable = ({ headers, data }) =&gt; {<br>  return (<br>    &lt;table&gt;<br>      &lt;thead&gt;<br>        &lt;tr&gt;<br>          {headers.map((header) =&gt; (<br>            &lt;th key={header.id}&gt;{header.label}&lt;/th&gt;<br>          ))}<br>        &lt;/tr&gt;<br>      &lt;/thead&gt;<br>      &lt;tbody&gt;<br>        {data.map((row, index) =&gt; (<br>          &lt;tr key={index}&gt;<br>            {headers.map((header) =&gt; (<br>              &lt;td key={header.id}&gt;<br>                {/* Conditional rendering inside the component */}<br>                {header.id === &#39;action&#39; ? (<br>                  &lt;button onClick={() =&gt; alert(`Action on ${row.name}`)}&gt;Action&lt;/button&gt;<br>                ) : header.id === &#39;options&#39; ? (<br>                  &lt;select&gt;<br>                    {row.options.map((option, idx) =&gt; (<br>                      &lt;option key={idx} value={option}&gt;<br>                        {option}<br>                      &lt;/option&gt;<br>                    ))}<br>                  &lt;/select&gt;<br>                ) : (<br>                  row[header.id]<br>                )}<br>              &lt;/td&gt;<br>            ))}<br>          &lt;/tr&gt;<br>        ))}<br>      &lt;/tbody&gt;<br>    &lt;/table&gt;<br>  );<br>};</pre><h4>Explanation:</h4><ul><li>The component accepts headers and data as props.</li><li>Conditional rendering is used within the component to check the header’s id (e.g., action or options) and render buttons or dropdowns accordingly.</li></ul><h3>Step 2: Introducing Render Props for Flexibility</h3><p>A better solution is to use <strong>render props</strong>, where we delegate rendering responsibility for each cell to a function provided via the header. This way, you can control how each cell is rendered without cluttering the CommonTable with conditional logic.</p><p>Here’s how to refactor the component using render props:</p><pre>const staticHeaders = [<br>  { id: &#39;name&#39;, label: &#39;Name&#39;, render: (row) =&gt; row.name },<br>  { id: &#39;age&#39;, label: &#39;Age&#39;, render: (row) =&gt; row.age },<br>  { id: &#39;location&#39;, label: &#39;Location&#39;, render: (row) =&gt; row.location },<br>  { id: &#39;action&#39;, label: &#39;Action&#39;, render: (row) =&gt; &lt;button onClick={() =&gt; alert(`Action on ${row.name}`)}&gt;Action&lt;/button&gt; },<br>  { id: &#39;options&#39;, label: &#39;Options&#39;, render: (row) =&gt; (<br>      &lt;select&gt;<br>        {row.options.map((option, idx) =&gt; (<br>          &lt;option key={idx} value={option}&gt;<br>            {option}<br>          &lt;/option&gt;<br>        ))}<br>      &lt;/select&gt;<br>    )<br>  },<br>];<br><br>const CommonTable = ({ headers, data }) =&gt; {<br>  return (<br>    &lt;table&gt;<br>      &lt;thead&gt;<br>        &lt;tr&gt;<br>          {headers.map((header) =&gt; (<br>            &lt;th key={header.id}&gt;{header.label}&lt;/th&gt;<br>          ))}<br>        &lt;/tr&gt;<br>      &lt;/thead&gt;<br>      &lt;tbody&gt;<br>        {data.map((row, index) =&gt; (<br>          &lt;tr key={index}&gt;<br>            {headers.map((header) =&gt; (<br>              &lt;td key={header.id}&gt;{header.render(row)}&lt;/td&gt;<br>            ))}<br>          &lt;/tr&gt;<br>        ))}<br>      &lt;/tbody&gt;<br>    &lt;/table&gt;<br>  );<br>};</pre><h4>Why This is Better:</h4><ul><li><strong>Flexibility</strong>: Instead of hard-coding the conditions in the table component, the rendering logic is defined in the render method of each header. You can now easily modify how each column is displayed.</li><li><strong>Scalability</strong>: As your requirements grow (e.g., adding new types of columns like images or checkboxes), you can handle it by simply updating the render method in the headers without touching the core CommonTable component.</li><li><strong>Separation of Concerns</strong>: The CommonTable no longer cares about how the cells are rendered. It simply delegates that responsibility to the render function, keeping the table logic clean and reusable.</li></ul><h3>Step 3: Using the Render Props Pattern in Your App</h3><p>Here’s how you would use this CommonTable in a real-world scenario:</p><pre>const data = [<br>  { name: &#39;John&#39;, age: 25, location: &#39;New York&#39;, options: [&#39;Edit&#39;, &#39;Delete&#39;] },<br>  { name: &#39;Jane&#39;, age: 30, location: &#39;London&#39;, options: [&#39;Edit&#39;, &#39;Archive&#39;] },<br>];<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Reusable Table with Render Props&lt;/h1&gt;<br>      &lt;CommonTable headers={staticHeaders} data={data} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>In this example, you can now easily modify how a column is rendered without touching the CommonTable. You simply update the render method in the staticHeaders array to change the behavior of that specific column.</p><h3>Conclusion</h3><p>Using normal props rendering with conditions inside the table component works for simple cases but can become cumbersome as the complexity of your application grows. By refactoring the table to use render props, you gain flexibility, scalability, and better separation of concerns. This pattern makes your table component much more powerful and adaptable to various rendering needs.</p><p>Whether you’re handling buttons, dropdowns, or custom UI elements, the render props pattern allows you to keep your table logic clean and focused while providing full control over how individual cells are rendered.</p><h3>Disclaimer</h3><p>The pattern of using render props is not just limited to table components — it’s a widely used practice for building <strong>reusable</strong> components in React. Whether it’s a form field, a card component, or a modal, render props provide flexibility, making your components more adaptable and easier to maintain.</p><p>Thank you for reading! If you found this content helpful, I’d like to extend a special thanks to <strong>ChatGPT</strong>, whose assistance made this article possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775f0812c136" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Does Create React App Do? Understanding Babel, Webpack, and More]]></title>
            <link>https://medium.com/@rakeshraj2097/what-does-create-react-app-do-understanding-babel-webpack-and-more-8a40b0ce9b19?source=rss-263365aced87------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a40b0ce9b19</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[how-cra-works]]></category>
            <category><![CDATA[react-cra]]></category>
            <category><![CDATA[babel]]></category>
            <dc:creator><![CDATA[Rakeshraj]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 17:01:09 GMT</pubDate>
            <atom:updated>2024-08-15T17:01:09.105Z</atom:updated>
            <content:encoded><![CDATA[<p>React is a powerful library for building user interfaces, and one of the tools that makes it incredibly accessible to developers is <strong>Create React App</strong> (CRA). CRA is a command-line utility that sets up a new React project with a good set of defaults, making it easy to start coding without worrying about the configuration details. In this post, we’ll dive into two key technologies that CRA leverages: Babel and Webpack, explaining how they work and why they are essential in a React project.</p><h3>Babel: Bridging the Gap Between Modern JavaScript and Browser Compatibility</h3><p>One of the first things that Create React App does is set up Babel, a JavaScript compiler that allows you to write modern JavaScript (ES2015+), including JSX, which is React’s syntax for writing HTML inside JavaScript. Babel converts this modern code into a form that older browsers can understand, ensuring your React application works across a wide range of environments.</p><p>For example, consider the following ES6 arrow function:</p><pre>const greet = () =&gt; console.log(&quot;Hello, World!&quot;);</pre><p>Babel will transpile this into an ES5 function, which can be understood by all browsers:</p><pre>var greet = function() {<br>  return console.log(&quot;Hello, World!&quot;);<br>};</pre><p>Babel is also responsible for transforming JSX into regular JavaScript. For instance, a JSX element like:</p><pre>const element = &lt;h1&gt;Hello, World!&lt;/h1&gt;;</pre><p>Is converted by Babel into:</p><pre>const element = React.createElement(&#39;h1&#39;, null, &#39;Hello, World!&#39;);</pre><h3>Babel’s Role in CRA</h3><p>To handle these transformations, Create React App configures several Babel packages:</p><ul><li><strong>@babel/core:</strong> This is the core Babel package that powers all of Babel&#39;s transformations. It&#39;s the engine that drives the conversion of your code.</li><li><strong>babel-loader:</strong> Webpack uses this loader to apply Babel transformations to your JavaScript files. When Webpack bundles your code, babel-loader ensures that the code is processed through Babel first.</li><li><strong>@babel/preset-env:</strong> This preset automatically determines the Babel plugins and polyfills you need based on your target browser environments. It simplifies the setup by allowing you to write modern JavaScript without worrying about browser compatibility.</li><li><strong>@babel/preset-react:</strong> This preset includes all the necessary plugins for transforming JSX and other React-specific syntax into JavaScript that browsers can understand.</li></ul><p>With these packages, CRA makes sure that your React code is modern, clean, and compatible with all the browsers you aim to support.</p><h3>Webpack: Bundling Your Application</h3><p>Another crucial piece of the Create React App setup is Webpack. Webpack is a module bundler that takes all your project’s various files — JavaScript, CSS, images, and more — and bundles them into a single or a few output files. This bundling is essential for a React application, where you might have multiple components and assets that need to be efficiently loaded in the browser.</p><p>When you’re building a React application, you’ll end up with numerous files: different components, stylesheets, images, etc. Webpack bundles all these into a single JavaScript file (or a few, depending on your setup), which can then be served alongside your index.html file. This process is vital because it ensures that all your assets are loaded correctly when your app runs in the browser.</p><h4>HTMLWebpackPlugin</h4><p>One of the key plugins that Webpack uses in a CRA setup is the <strong>HTMLWebpackPlugin</strong>. This plugin generates an index.html file for your application, automatically injecting your bundled JavaScript into it. It ensures that your app loads correctly with all its dependencies in place.</p><p>Here’s an example of a basic Webpack configuration that includes the HTMLWebpackPlugin:</p><pre>const path = require(&#39;path&#39;);<br>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);<br><br>module.exports = {<br>  entry: &#39;./src/index.js&#39;,<br>  output: {<br>    path: path.resolve(__dirname, &#39;dist&#39;),<br>    filename: &#39;bundle.js&#39;<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.js$/,<br>        exclude: /node_modules/,<br>        use: {<br>          loader: &#39;babel-loader&#39;<br>        }<br>      }<br>    ]<br>  },<br>  plugins: [<br>    new HtmlWebpackPlugin({<br>      template: &#39;./src/index.html&#39;<br>    })<br>  ]<br>};</pre><p>In this configuration:</p><ul><li><strong>entry:</strong> This specifies the entry point of your application. Webpack will start bundling from this file.</li><li><strong>output:</strong> This defines where the bundled files should be outputted and the name of the bundle.</li><li><strong>module.rules:</strong> This array specifies the loaders to use for different file types. Here, Babel is applied to all .js files.</li><li><strong>plugins:</strong> This array includes plugins like HTMLWebpackPlugin, which automates the creation of your index.html and injects your bundled JavaScript.</li></ul><h3>Conclusion</h3><p>Create React App simplifies the process of getting started with React by configuring essential tools like Babel and Webpack out of the box. Babel ensures your modern JavaScript and JSX run across all browsers, while Webpack efficiently bundles your assets to be served with your application. While this post highlights two key components, there is much more that CRA handles behind the scenes, from optimizing your app for production to managing development servers. Understanding how these tools work under the hood can help you better appreciate the convenience that CRA offers and enable you to customize your setup as your project grows.</p><p>Happy coding!</p><h3>Courtesy</h3><p>This article was written with insights provided by <a href="https://chat.openai.com/">ChatGPT</a>. For more in-depth information on Babel and Webpack, you can refer to their official documentation:</p><ul><li><a href="https://babeljs.io/">Babel Documentation</a></li><li><a href="https://webpack.js.org/">Webpack Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a40b0ce9b19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React: How It Works Under the Hood]]></title>
            <link>https://medium.com/@rakeshraj2097/understanding-react-how-it-works-under-the-hood-5a70c6350946?source=rss-263365aced87------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a70c6350946</guid>
            <dc:creator><![CDATA[Rakeshraj]]></dc:creator>
            <pubDate>Sun, 21 Jul 2024 17:11:41 GMT</pubDate>
            <atom:updated>2024-07-21T17:11:41.249Z</atom:updated>
            <content:encoded><![CDATA[<p>React has become one of the most popular libraries for building user interfaces, thanks to its efficiency, flexibility, and simplicity. To truly appreciate the power of React, it helps to understand what happens under the hood. In this blog post, we’ll delve into three core aspects: reconciliation, the diffing algorithm, and the key prop used in rendering child components.</p><h4>🚀Reconciliation</h4><p>Reconciliation is the process by which React updates the DOM. When the state or props of a React component change, React needs to figure out how to update the UI to reflect those changes. Instead of updating the entire DOM, which can be slow and inefficient, React updates only the parts of the DOM that have changed. This process is called reconciliation.</p><p>During reconciliation, React creates a virtual DOM — a lightweight copy of the actual DOM. When a component’s state changes, React creates a new virtual DOM tree and compares it to the previous one. This comparison helps React determine the minimum number of changes needed to update the actual DOM.</p><h4>🚀The Diffing Algorithm</h4><p>The process of comparing the new virtual DOM tree with the old one is known as the diffing algorithm. The diffing algorithm is central to React’s performance, as it efficiently determines which parts of the DOM need to be updated.</p><p>The algorithm works by following these steps:</p><p><strong>⭐Elements of Different Types:</strong></p><p>When the root elements have different types, React will tear down the old tree and build the new one from scratch. For example, changing from &lt;a&gt; to &lt;img&gt;, or from &lt;Article&gt; to &lt;Comment&gt;, will lead to a full rebuild.</p><p>When tearing down a tree, old DOM nodes are destroyed, and component instances receive componentWillUnmount(). When building a new tree, new DOM nodes are inserted, and component instances receive componentDidMount(). Any state associated with the old tree is lost.</p><p>Consider the following example:</p><pre>&lt;div&gt;<br> &lt;Counter /&gt;<br>&lt;/div&gt;<br>&lt;span&gt;<br> &lt;Counter /&gt;<br>&lt;/span&gt;</pre><p>This change will destroy the old Counter instance and remount a new one.</p><p>⭐ <strong>DOM Elements of the Same Type:</strong></p><p>When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes. For instance:</p><pre>&lt;div className=&quot;before&quot; title=&quot;stuff&quot; /&gt;<br>&lt;div className=&quot;after&quot; title=&quot;stuff&quot; /&gt;</pre><p>React will update only the className attribute on the underlying DOM node. Similarly, when updating style, React only modifies the properties that changed:</p><pre>&lt;div style={{color: &#39;red&#39;, fontWeight: &#39;bold&#39;}} /&gt;<br>&lt;div style={{color: &#39;green&#39;, fontWeight: &#39;bold&#39;}} /&gt;</pre><p>React will update only the color style, not fontWeight.</p><p>After handling the DOM node, React recurses on the children.</p><p>⭐<strong> Component Elements of the Same Type:</strong></p><p>When a component updates, the instance remains the same, maintaining the state across renders. React updates the props of the underlying component instance to match the new element and calls getSnapshotBeforeUpdate() and componentDidUpdate() on the instance.</p><p>Next, the render() method is called, and the diff algorithm recurses on the previous and new results.</p><p>⭐<strong> Recursing on Children:</strong></p><p>By default, when recursing on the children of a DOM node, React iterates over both lists of children simultaneously and generates a mutation whenever there’s a difference.</p><p>For example, adding an element at the end of the children:</p><pre>&lt;ul&gt;<br> &lt;li&gt;first&lt;/li&gt;<br> &lt;li&gt;second&lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;ul&gt;<br> &lt;li&gt;first&lt;/li&gt;<br> &lt;li&gt;second&lt;/li&gt;<br> &lt;li&gt;third&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>React will match the two &lt;li&gt;first&lt;/li&gt; trees, the two &lt;li&gt;second&lt;/li&gt; trees, and then insert the &lt;li&gt;third&lt;/li&gt; tree.</p><p>Inserting an element at the beginning can lead to poor performance:</p><pre>&lt;ul&gt;<br> &lt;li&gt;Duke&lt;/li&gt;<br> &lt;li&gt;Villanova&lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;ul&gt;<br> &lt;li&gt;Connecticut&lt;/li&gt;<br> &lt;li&gt;Duke&lt;/li&gt;<br> &lt;li&gt;Villanova&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>React will mutate every child instead of realizing it can keep the &lt;li&gt;Duke&lt;/li&gt; and &lt;li&gt;Villanova&lt;/li&gt; subtrees intact.</p><p>🚀 <strong>Keys:</strong></p><p>To solve this issue, React supports a key attribute. When children have keys, React uses the key to match children in the original tree with those in the subsequent tree. For example:</p><pre>&lt;ul&gt;<br> &lt;li key=&quot;2015&quot;&gt;Duke&lt;/li&gt;<br> &lt;li key=&quot;2016&quot;&gt;Villanova&lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;ul&gt;<br> &lt;li key=&quot;2014&quot;&gt;Connecticut&lt;/li&gt;<br> &lt;li key=&quot;2015&quot;&gt;Duke&lt;/li&gt;<br> &lt;li key=&quot;2016&quot;&gt;Villanova&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>React knows the element with key ‘2014’ is new, and the elements with keys ‘2015’ and ‘2016’ have just moved.</p><p>Finding a key is usually straightforward, as the element may already have a unique ID:</p><pre>&lt;li key={item.id}&gt;{item.name}&lt;/li&gt;</pre><p>As a last resort, you can use the item’s index in the array as a key. This works well if items are never reordered, but reorders will be slow and can cause issues with component state. For instance, moving an item changes its key if the key is an index, which can mix up component state in unexpected ways.</p><p><strong>Conclusion</strong></p><p>Understanding the diffing algorithm &amp; Reconciliation helps you write efficient and effective React code. By leveraging keys properly, you can optimize your application’s performance and ensure a smooth user experience.</p><h4>👏Courtesy</h4><p>This blog post was inspired by the <a href="https://react.dev/blog/2023/03/16/introducing-react-dev">React documentation </a>and insights from ChatGPT. Special thanks to both for providing detailed explanations and valuable information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a70c6350946" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Request Handling in React with Axios and AbortController]]></title>
            <link>https://medium.com/@rakeshraj2097/efficient-request-handling-in-react-with-axios-and-abortcontroller-e47bafab87c9?source=rss-263365aced87------2</link>
            <guid isPermaLink="false">https://medium.com/p/e47bafab87c9</guid>
            <dc:creator><![CDATA[Rakeshraj]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 17:22:57 GMT</pubDate>
            <atom:updated>2024-06-12T17:22:57.373Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In modern web applications, managing HTTP requests efficiently is crucial, especially when dealing with dynamic and interactive user interfaces. One common challenge is the need to cancel pending requests to avoid unnecessary network traffic and improve performance. In this blog post, we’ll explore how to use Axios, a popular HTTP client, in conjunction with the AbortController to handle request cancellation effectively.</p><h3>What is AbortController?</h3><p>The AbortController interface represents a controller object that allows you to abort one or more DOM requests as and when desired. AbortController can be used to abort fetch requests, which is particularly useful for canceling HTTP requests in a web application.</p><h3>Why Use AbortController with Axios?</h3><p>When dealing with HTTP requests in a web application, there are scenarios where you might need to cancel a request. For example:</p><ul><li>A user navigates away from a page before a request completes.</li><li>A new request is made that renders the previous one obsolete.</li><li>To avoid race conditions in search functionalities.</li></ul><p>Using AbortController with <a href="https://axios-http.com/docs/">Axios</a> can help you handle these situations gracefully.</p><p>Enough with the theory — let’s dive into some real-world examples!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Xhf5ejri8w9KpOcygtWVgg.gif" /><figcaption>Video shows the Multiple Api Requests</figcaption></figure><p>The video illustrates how Axios operates without AbortController. With every click or client request, Axios triggers multiple API calls, significantly increasing API traffic.</p><p>The code for above looks like :</p><pre>const useFetchApi = () =&gt; {<br>    const [fetchData, setFetchData] = useState(null);<br>    const [error, setError] = useState(null);<br>    const [loading, setLoading] = useState(false);<br>    const baseURL =&quot;https://jsonplaceholder.typicode.com/&quot;<br>    const abortControllerRef = useRef(null);<br><br>    const handleApi = useCallback(async (url, method = &#39;GET&#39;, data = null) =&gt; {<br>        setLoading(true);<br>        setError(null);<br>      <br>        try {<br>            const axiosInstance = axios.create({<br>                baseURL,<br>            });<br><br>            const response = await axiosInstance({<br>                method,<br>                url,<br>                data,<br>            });<br><br>            setFetchData(response.data);<br>        } catch (err) {<br>            if (axios.isCancel(err)) {<br>                console.log(&#39;Request canceled&#39;, err.message);<br>            }<br>            else {<br>                setError(err);<br>            }<br>        } finally {<br>            setLoading(false);<br>        }<br>    }, []);<br><br>    return { fetchData, error, loading, handleApi };<br>};<br><br>export default useFetchApi;</pre><p><strong>Adding AbortController to Axios</strong></p><p>To incorporate AbortController with Axios and streamline request handling, we need to make a few adjustments to our existing code. Let’s walk through the modifications:</p><pre>const useFetchApi = () =&gt; {<br>    const [fetchData, setFetchData] = useState(null);<br>    const [error, setError] = useState(null);<br>    const [loading, setLoading] = useState(false);<br>    const baseURL =&quot;https://jsonplaceholder.typicode.com/&quot;<br><br>  // Reference for AbortController<br>    const abortControllerRef = useRef(null);<br><br>    const handleApi = useCallback(async (url, method = &#39;GET&#39;, data = null) =&gt; {<br>        setLoading(true);<br>        setError(null);<br>   // checking the presence of previous request <br>        if (abortControllerRef.current) {<br>            abortControllerRef.current.abort();<br>        }<br>         abortControllerRef.current = new AbortController();<br>   // Getting Signal to Abort from the controller<br>         const { signal } = abortControllerRef.current;<br>        try {<br>            const axiosInstance = axios.create({<br>                baseURL,<br>            });<br><br>            const response = await axiosInstance({<br>                method,<br>                url,<br>                data,<br>   // Associate the instance with the Signal<br>                signal<br>            });<br><br>            setFetchData(response.data);<br>        } catch (err) {<br>            if (axios.isCancel(err)) {<br>                console.log(&#39;Request canceled&#39;, err.message);<br>            }<br>            else {<br>                setError(err);<br>            }<br>        } finally {<br>            setLoading(false);<br>        }<br>    }, []);<br>    useEffect(() =&gt; {<br>        // Cleanup function to abort the request if the component unmounts<br>        return () =&gt; {<br>            if (abortControllerRef.current) {<br>                abortControllerRef.current.abort();<br>            }<br>        };<br>    }, []);<br><br>    return { fetchData, error, loading, handleApi };<br>};<br><br>export default useFetchApi;</pre><p>And Now it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*H_wY1mFmw2xCX5JMEyrkGQ.gif" /><figcaption>Request Getting cancelled</figcaption></figure><p>Certainly! By integrating AbortController with Axios in your React applications, you can efficiently manage HTTP requests and ensure optimal performance. This approach empowers you to gracefully handle scenarios where request cancellation is necessary, enhancing the overall user experience.Try it out in your projects and see the difference it makes!</p><h3>Further Reading</h3><ul><li>Axios <a href="https://axios-http.com/docs/">Documentation</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController">AbortController Documentation on MDN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e47bafab87c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>