<?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 Manappa Kammar on Medium]]></title>
        <description><![CDATA[Stories by Manappa Kammar on Medium]]></description>
        <link>https://medium.com/@manappa.kammar777?source=rss-87889aec0439------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nT_443uGfBM_pubC</url>
            <title>Stories by Manappa Kammar on Medium</title>
            <link>https://medium.com/@manappa.kammar777?source=rss-87889aec0439------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 17:40:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manappa.kammar777/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[JavaScript Memory Management: From Object Allocation to Garbage Collection]]></title>
            <link>https://medium.com/@manappa.kammar777/javascript-memory-management-from-object-allocation-to-garbage-collection-5095198e76cb?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/5095198e76cb</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 16:52:29 GMT</pubDate>
            <atom:updated>2026-08-09T16:57:27.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVSr3HdIn_FvVh2Ya5bddw.png" /><figcaption>Garbage Collection</figcaption></figure><p>Garbage Collection is one of those JavaScript concepts that looks complicated at first.</p><p>You hear terms like:</p><ul><li>Heap</li><li>Stack</li><li>GC Roots</li><li>Mark &amp; Sweep</li><li>Reachability</li><li>Generational GC</li><li>Minor GC</li><li>Major GC</li><li>Memory Leak</li></ul><p>But the core idea is actually very simple:</p><blockquote><strong><em>If an object is no longer reachable by the JavaScript program, the Garbage Collector can eventually clean it up.</em></strong></blockquote><p>Let’s understand this step by step.</p><h3>1. Why do we need Garbage Collection?</h3><p>When JavaScript creates objects, arrays, functions, etc., memory is required to store them.</p><p>For example:</p><pre>const user = {<br>  name: &quot;John&quot;,<br>  age: 30<br>};</pre><p>Conceptually, we can think of it like:</p><pre>Variable<br>   |<br>   ↓<br> user<br>   |<br>   ↓<br>┌─────────────────┐<br>│ name: &quot;John&quot;    │<br>│ age: 30         │<br>└─────────────────┘<br>       Heap</pre><p>The user variable holds a reference to the object.</p><p>As long as the object is reachable, JavaScript considers it still usable.</p><h3>2. What is the Heap?</h3><p>The <strong>heap</strong> is an area of memory where JavaScript engines store dynamically allocated data such as objects and arrays.</p><p>For example:</p><pre>const user = {<br>  name: &quot;John&quot;<br>};<br><br>const numbers = [10, 20, 30];</pre><pre>Heap<br>        ┌─────────────────────┐<br>        │                     │<br>user ───────→ { name: &quot;John&quot; }│<br>        │                     │<br>numbers ───→ [10,20,30]       │<br>        │                     │<br>        └─────────────────────┘</pre><p>The important thing to understand is:</p><blockquote><em>Variables can hold references to objects that live in the heap.</em></blockquote><p>The exact implementation details of Stack and Heap are engine-specific, but this mental model is very useful for understanding GC.</p><h3>3. What is Reachability?</h3><p>This is the most important concept in Garbage Collection.</p><p>Imagine:</p><pre>let user = {<br>  name: &quot;John&quot;<br>};</pre><p>We have:</p><pre>GC Root<br>   |<br>   ↓<br> user<br>   |<br>   ↓<br>Object</pre><p>The object is reachable.</p><p>Therefore:</p><pre>Object → KEEP</pre><p>Now:</p><pre>user = null;</pre><p>We get:</p><pre>GC Root<br>   |<br>   ↓<br> user → null<br></pre><pre>Heap:</pre><pre>{ name: &quot;John&quot; }<br>       ↑<br>     nobody</pre><p>The object is now unreachable.</p><p>It becomes <strong>eligible for garbage collection</strong>.</p><p>Notice the wording:</p><blockquote><em>“Eligible for garbage collection”</em></blockquote><p>It does NOT mean the object is necessarily deleted immediately.</p><p>The GC runs according to the engine’s own strategy.</p><h3>4. Your First Example</h3><p>Let’s look at this code:</p><pre>function addUser() {<br>  const users = [];<br>  users.push({<br>    name: &quot;John&quot;<br>  });<br>}<br><br>addUser();</pre><p>Let’s execute it step by step.</p><h3>Step 1: Function is called</h3><pre>addUser();</pre><p>JavaScript creates an execution context for the function.</p><p>Conceptually:</p><pre>addUser()<br>   |<br>   ↓<br>users<br>   |<br>   ↓<br>[]</pre><p>Then:</p><pre>users.push({<br>  name: &quot;John&quot;<br>});</pre><p>The array now contains an object:</p><pre>users<br>   |<br>   ↓<br>┌─────────────────┐<br>│ { name: &quot;John&quot; }│<br>└─────────────────┘</pre><h3>Step 2: Function finishes</h3><p>The function reaches:</p><pre>}</pre><p>and execution finishes.</p><p>The local variable:</p><pre>const users</pre><p>was created inside addUser().</p><p>Nothing outside the function has a reference to that array.</p><p>Conceptually:</p><pre>addUser() finished</pre><pre>users ─────X────→ [ { name: &quot;John&quot; } ]</pre><pre>                  ↑<br>               nobody</pre><p>The array is unreachable.</p><p>But there is another important detail.</p><p>The object inside the array is also unreachable.</p><p>So:</p><pre>Array<br>  |<br>  ↓<br>Object</pre><p>Both can eventually be collected.</p><pre>Array → 🗑️<br>Object → 🗑️</pre><h3>5. Calling the First Function Multiple Times</h3><p>Suppose:</p><pre>addUser();<br>addUser();<br>addUser();</pre><p>Each call creates its own local users array.</p><p>Conceptually:</p><pre>Call 1<br>  ↓<br>users → [Object]<br>  ↓<br>function finishes<br>  ↓<br>unreachable<br>  ↓<br>eligible for GC<br></pre><pre>Call 2<br>  ↓<br>users → [Object]<br>  ↓<br>function finishes<br>  ↓<br>unreachable<br>  ↓<br>eligible for GC<br></pre><pre>Call 3<br>  ↓<br>users → [Object]<br>  ↓<br>function finishes<br>  ↓<br>unreachable<br>  ↓<br>eligible for GC</pre><p>Therefore, simply creating objects inside a function does <strong>not</strong> automatically cause a memory leak.</p><h3>6. Now Look at Your Second Example</h3><p>This is different:</p><pre>const users = [];<br><br>function addUser() {<br>  users.push({<br>    name: &quot;John&quot;<br>  });<br>}<br>addUser();</pre><p>Here:</p><pre>const users = [];</pre><p>exists outside the function.</p><p>Conceptually:</p><pre>GC Root<br>   |<br>   ↓<br> users<br>   |<br>   ↓<br> []</pre><p>Now we call:</p><pre>addUser();</pre><p>The function adds an object:</p><pre>GC Root<br>   |<br>   ↓<br> users<br>   |<br>   ↓<br>┌─────────────────┐<br>│ { name: &quot;John&quot; }│<br>└─────────────────┘</pre><p>The object is still reachable through users.</p><p>Therefore:</p><pre>Object → KEEP</pre><h3>7. What Happens When We Call It Again?</h3><pre>addUser();<br>addUser();<br>addUser();</pre><p>The array keeps growing:</p><pre>users<br>  |<br>  ├── Object 1<br>  ├── Object 2<br>  ├── Object 3<br>  └── Object 4</pre><p>All of these objects are reachable.</p><p>Therefore:</p><pre>Object 1 → reachable → KEEP<br>Object 2 → reachable → KEEP<br>Object 3 → reachable → KEEP<br>Object 4 → reachable → KEEP</pre><p>The Garbage Collector cannot simply delete them.</p><p>Why?</p><p>Because from the program’s perspective, they are still accessible:</p><pre>users[0]<br>users[1]<br>users[2]<br>users[3]</pre><h3>8. Is the Second Example Automatically a Memory Leak?</h3><p>No.</p><p>This is extremely important.</p><pre>const users = [];<br><br>function addUser() {<br>  users.push({<br>    name: &quot;John&quot;<br>  });<br>}</pre><p>is not automatically a memory leak.</p><p>If your application genuinely needs these users, keeping them in memory is correct.</p><p>It becomes a problem when:</p><blockquote><em>Objects remain reachable even though the application no longer needs them.</em></blockquote><p>For example:</p><pre>const users = [];<br><br>function addUser() {<br>  users.push({<br>    name: &quot;John&quot;<br>  });<br>}<br><br>for (let i = 0; i &lt; 1000000; i++) {<br>  addUser();<br>}</pre><p>Now potentially a very large number of objects are retained.</p><p>The GC says:</p><pre>&quot;I can see that users references the array.&quot;</pre><pre>&quot;The array references these objects.&quot;</pre><pre>&quot;Therefore they are reachable.&quot;</pre><pre>&quot;I cannot safely delete them.&quot;</pre><p>This can cause memory to keep growing.</p><h3>9. The Garbage Collector’s Basic Algorithm</h3><p>A simplified garbage collector can be understood using:</p><h3>Mark → Sweep</h3><p>Imagine:</p><pre>GC Root<br>   |<br>   ↓<br> A → B → C<br><br> D → E<br><br> F</pre><p>Suppose only A is reachable from a GC root.</p><p>The GC starts at the root and follows references.</p><p>It marks:</p><pre>A ✓<br>B ✓<br>C ✓</pre><p>But:</p><pre>D ✗<br>E ✗<br>F ✗</pre><p>cannot be reached.</p><p>Then the collector can reclaim the unreachable objects.</p><pre>MARK</pre><pre>A ✓<br>B ✓<br>C ✓</pre><pre>D ✗<br>E ✗<br>F ✗</pre><pre>        ↓</pre><pre>SWEEP</pre><pre>Remove unreachable objects</pre><p>That’s the basic idea behind <strong>Mark-and-Sweep</strong>.</p><p>Modern JavaScript engines use much more sophisticated techniques, but this is the foundation.</p><h3>10. What Are GC Roots?</h3><p>The GC needs a starting point.</p><p>These starting points are called <strong>GC Roots</strong>.</p><p>The exact implementation is engine-specific, but conceptually they can include:</p><ul><li>Global objects</li><li>Active execution contexts</li><li>Variables currently reachable from running code</li><li>Closures</li><li>Runtime/engine references</li></ul><p>The GC starts from these roots and follows references.</p><p>For example:</p><pre>GC Root<br>   |<br>   ↓<br>users<br>   |<br>   ↓<br>Array<br>   |<br>   ├── Object A<br>   ├── Object B<br>   └── Object C</pre><p>Everything reachable from the root is considered alive.</p><h3>11. A Very Important Rule</h3><p>Don’t think:</p><blockquote><em>“This variable went out of scope, therefore GC immediately deletes everything.”</em></blockquote><p>Instead think:</p><blockquote><strong><em>“If an object is no longer reachable from any GC root, it becomes eligible for garbage collection.”</em></strong></blockquote><p>That’s much more accurate.</p><h3>12. What About Objects Referencing Other Objects?</h3><p>Consider:</p><pre>const user = {<br>  name: &quot;John&quot;,<br>  address: {<br>    city: &quot;Bangalore&quot;<br>  }<br>};</pre><p>Conceptually:</p><pre>GC Root<br>   |<br>   ↓<br> user<br>   |<br>   ↓<br>User Object<br>   |<br>   ↓<br>Address Object</pre><p>Both objects are reachable.</p><p>Now:</p><pre>user = null;</pre><p>If there are no other references:</p><pre>GC Root</pre><pre>user → null<br></pre><pre>User Object<br>     |<br>     ↓<br>Address Object</pre><pre>Nobody can reach them</pre><p>The entire object graph can become collectible.</p><p>So GC works with <strong>object graphs</strong>, not just individual variables.</p><h3>13. Memory Leak Example: Event Listener</h3><p>A common real-world problem:</p><pre>element.addEventListener(&quot;click&quot;, handler);</pre><p>If the listener and related references remain registered unnecessarily, objects associated with that code can remain reachable longer than intended.</p><p>That’s why cleanup matters.</p><h3>14. React Example</h3><p>This is especially important in React.</p><p>Consider:</p><pre>useEffect(() =&gt; {<br>  const timer = setInterval(() =&gt; {<br>    console.log(&quot;Hello&quot;);<br>  }, 1000);<br>}, []);</pre><p>The component creates a timer.</p><p>If the component disappears, you generally want to clean up the timer:</p><pre>useEffect(() =&gt; {<br>  const timer = setInterval(() =&gt; {<br>    console.log(&quot;Hello&quot;);<br>  }, 1000);<br><br>  return () =&gt; {<br>    clearInterval(timer);<br>  };<br>}, []);</pre><p>The cleanup function removes the timer when the effect is no longer needed.</p><p>This helps prevent unnecessary resources and references from remaining active.</p><h3>15. Generational Garbage Collection</h3><p>Now that reachability is clear, we can understand the next concept.</p><p>Modern engines such as V8 use <strong>generational garbage collection</strong>.</p><p>The basic observation is:</p><blockquote><em>Most newly created objects become unused quickly.</em></blockquote><p>So memory is broadly organized into generations.</p><pre>Young Generation<br>       ↓<br>New objects<br>       ↓<br>Do they survive?<br>    ↙       ↘<br>   NO       YES<br>   ↓         ↓<br>Collect    Survive<br>             ↓<br>        Eventually promoted<br>             ↓<br>       Old Generation</pre><p>Young objects can be collected frequently.</p><p>Long-lived objects are treated differently.</p><p>This makes garbage collection more efficient.</p><h3>16. The Complete Mental Model</h3><p>You can remember JavaScript Garbage Collection using this flow:</p><pre>JavaScript creates object<br>          ↓<br>Object stored in memory<br>          ↓<br>Some variable/reference points to it<br>          ↓<br>Object is reachable<br>          ↓<br>GC keeps it<br>          ↓<br>Reference disappears<br>          ↓<br>Is there another path to the object?<br>       ↙             ↘<br>     YES              NO<br>      ↓                ↓<br>   Keep it          Unreachable<br>                       ↓<br>                  Eligible for GC<br>                       ↓<br>               Memory reclaimed</pre><h3>17. The Most Important Comparison</h3><h3>Example 1</h3><pre>function addUser() {<br>  const users = [];<br>  users.push({<br>    name: &quot;John&quot;<br>  });<br>}</pre><p>Flow:</p><pre>Call function<br>     ↓<br>Create users<br>     ↓<br>Add object<br>     ↓<br>Function finishes<br>     ↓<br>No reference to users<br>     ↓<br>users becomes unreachable<br>     ↓<br>Object becomes unreachable<br>     ↓<br>Eligible for GC</pre><h3>Example 2</h3><pre>const users = [];<br><br>function addUser() {<br>  users.push({<br>    name: &quot;John&quot;<br>  });<br>}</pre><p>Flow:</p><pre>Create users<br>     ↓<br>users remains reachable<br>     ↓<br>Call addUser()<br>     ↓<br>Add object<br>     ↓<br>users → object<br>     ↓<br>Object is reachable<br>     ↓<br>GC keeps it</pre><p>If you keep adding objects:</p><pre>users<br>  ↓<br>Object<br>Object<br>Object<br>Object<br>Object<br>...</pre><p>they remain reachable until you remove them or otherwise break the references.</p><h4><strong>“How does Garbage Collection work in JavaScript?”</strong></h4><blockquote><em>“JavaScript uses automatic garbage collection to reclaim memory that is no longer reachable. The garbage collector starts from GC roots and follows references to determine which objects are still reachable. Unreachable objects become eligible for collection. A simplified way to understand this is Mark-and-Sweep: mark reachable objects and reclaim the memory of unreachable objects. Modern engines such as V8 also use generational and incremental techniques to improve performance and reduce pauses.”</em></blockquote><h4><strong>“What causes memory leaks?”</strong></h4><blockquote><em>“A memory leak occurs when objects that are no longer needed remain reachable through references, so the garbage collector cannot reclaim them. Common examples include accidentally retained global references, event listeners, timers, subscriptions, caches, and closures.”</em></blockquote><h3><strong>“Garbage Collection is not about deleting unused variables; it is about finding objects that are no longer reachable and reclaiming their memory.”</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5095198e76cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Changing a Nested Object Updates the Original: Understanding Shallow Copy and Structural…]]></title>
            <link>https://medium.com/@manappa.kammar777/why-changing-a-nested-object-updates-the-original-understanding-shallow-copy-and-structural-d5c3730c958a?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5c3730c958a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 16:43:51 GMT</pubDate>
            <atom:updated>2026-06-27T16:43:51.147Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Changing a Nested Object Updates the Original: Understanding Shallow Copy and Structural Sharing in JavaScript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSgjdWq2O-Oxj8njUSZoQQ.png" /></figure><h3>JavaScript: Shallow Copy vs Structural Sharing — The Concept That Finally Clicked for Me</h3><p>As JavaScript developers, we use the spread operator (...) almost every day.</p><pre>const newObj = { ...oldObj };</pre><p>But do we really understand what’s happening under the hood?</p><p>I recently spent time deeply understanding two concepts that are often confused:</p><ul><li><strong>Shallow Copy</strong></li><li><strong>Structural Sharing</strong></li></ul><p>At first, both looked identical to me because both involve sharing references. But after digging deeper, I realized they’re completely different things.</p><p>This article explains the difference in the simplest way possible.</p><h3>Understanding Objects in JavaScript</h3><p>Consider this object:</p><pre>const user = {<br>  name: &quot;John&quot;,<br>  address: {<br>    city: &quot;Bangalore&quot;<br>  }<br>};</pre><p>Memory representation:</p><pre>user<br> ├── name -&gt; &quot;John&quot;<br> └── address -&gt; Object #1<br>                   └── city -&gt; &quot;Bangalore&quot;</pre><p>The address property doesn&#39;t contain the actual object.</p><p>It contains a <strong>reference</strong> (pointer) to another object in memory.</p><h3>What is a Shallow Copy?</h3><p>Let’s create a copy.</p><pre>const copiedUser = {<br>  ...user<br>};</pre><p>Many developers think this creates a completely independent object.</p><p>It doesn’t.</p><p>JavaScript internally does something similar to:</p><pre>copiedUser.name = user.name;<br>copiedUser.address = user.address;</pre><p>Notice this line:</p><pre>copiedUser.address = user.address;</pre><p>The nested object isn’t copied.</p><p>Its reference is copied.</p><p>Memory now looks like this:</p><pre>user                           copiedUser<br> ├── name                      ├── name<br> └── address ───────┐          └── address ───────┐<br>                    │                            │<br>                    └──────── Object #1 ◄────────┘<br>                               city = &quot;Bangalore&quot;</pre><p>Both objects point to the same address object.</p><h3>Why Does This Work?</h3><p>Changing a top-level property:</p><pre>copiedUser.name = &quot;David&quot;;</pre><pre>console.log(user.name);       // John<br>console.log(copiedUser.name); // David</pre><p>Output:</p><pre>John<br>David</pre><p>Because strings are primitive values and were copied.</p><h3>The Confusing Part</h3><pre>copiedUser.address.city = &quot;Mumbai&quot;;</pre><pre>console.log(user.address.city);<br>console.log(copiedUser.address.city);</pre><p>Output:</p><pre>Mumbai<br>Mumbai</pre><p>Why did the original object change?</p><p>Because there is only one address object.</p><pre>user.address<br>      │<br>      ▼<br>   Object #1<br>      ▲<br>      │<br>copiedUser.address</pre><p>You changed Object #1 itself.</p><p>Both variables are pointing to the same object.</p><p>You can prove it:</p><pre>console.log(user.address === copiedUser.address);</pre><p>Output:</p><pre>true</pre><p>This true explains everything.</p><h3>Creating a Truly Independent Nested Object</h3><pre>const copiedUser = {<br>  ...user,<br>  address: {<br>    ...user.address<br>  }<br>};</pre><p>Now:</p><pre>copiedUser.address.city = &quot;Mumbai&quot;;</pre><pre>console.log(user.address.city);</pre><p>Output:</p><pre>Bangalore</pre><p>Because now:</p><pre>user.address --------&gt; Object #1</pre><pre>copiedUser.address --&gt; Object #2</pre><p>Two separate objects exist.</p><h3>So, What Exactly Is a Shallow Copy?</h3><p>A shallow copy:</p><ul><li>Creates a new top-level object.</li><li>Copies primitive values.</li><li>Copies references of nested objects.</li></ul><p>Think of it as:</p><blockquote><em>“Copy the first layer only.”</em></blockquote><h3>Then What Is Structural Sharing?</h3><p>This is where many developers get confused.</p><p>Structural sharing is <strong>not another type of copy</strong>.</p><p>It’s an <strong>update strategy</strong>.</p><p>Its goal is:</p><pre>Copy only what changed.<br>Reuse everything else.</pre><h3>Real Example</h3><pre>const state = {<br>  user: {<br>    profile: {<br>      name: &quot;John&quot;<br>    }<br>  },<br>  cart: {<br>    items: [&quot;Phone&quot;, &quot;Laptop&quot;]<br>  },<br>  settings: {<br>    theme: &quot;dark&quot;<br>  }<br>};</pre><p>Suppose we only change the user’s name.</p><pre>const newState = {<br>  ...state,<br>  user: {<br>    ...state.user,<br>    profile: {<br>      ...state.user.profile,<br>      name: &quot;David&quot;<br>    }<br>  }<br>};</pre><h3>What Actually Happened?</h3><p>New objects:</p><ul><li>newState</li><li>newState.user</li><li>newState.user.profile</li></ul><p>Reused objects:</p><ul><li>cart</li><li>settings</li></ul><pre>console.log(state.cart === newState.cart);<br>// true</pre><pre>console.log(state.settings === newState.settings);<br>// true</pre><p>Memory:</p><pre>OLD STATE</pre><pre>state<br> ├─ user ------ Object A<br> ├─ cart ------ Object B<br> └─ settings -- Object C<br></pre><pre>NEW STATE</pre><pre>newState<br> ├─ user ------ Object D (new)<br> ├─ cart ------ Object B (reused)<br> └─ settings -- Object C (reused)</pre><p>Only the changed branch was recreated.</p><p>Everything else was shared.</p><p>This is called <strong>Structural Sharing</strong>.</p><h3>The Line That Finally Made It Click</h3><h3>Shallow Copy is a Tool.</h3><pre>{ ...obj }</pre><p>This is simply an operation that creates a new object and copies references.</p><h3>Structural Sharing is a Strategy.</h3><p>Its purpose is:</p><pre>Create new objects only where data changed.<br>Reuse everything else.</pre><p>To achieve that goal, it uses shallow copies internally.</p><h3>Final Takeaways</h3><h3>Shallow Copy</h3><p>✅ New top-level object</p><p>✅ Nested references are shared</p><p>❌ Not a deep copy</p><h3>Structural Sharing</h3><p>✅ Immutable update technique</p><p>✅ Copies only the changed path</p><p>✅ Reuses unchanged objects</p><p>✅ Memory efficient</p><p>✅ Faster reference comparisons</p><h3>One-Line Answer</h3><blockquote><em>A shallow copy creates a new top-level object while nested objects keep the same references. Structural sharing is an immutable update strategy that uses shallow copies to recreate only the changed parts of an object graph while reusing everything else.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5c3730c958a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Deleting Object Properties Can Hurt V8 Performance: Understanding Hidden Classes…]]></title>
            <link>https://medium.com/@manappa.kammar777/why-deleting-object-properties-can-hurt-v8-performance-understanding-hidden-classes-93f3bfd7de01?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/93f3bfd7de01</guid>
            <category><![CDATA[javascript-engine]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 17:16:55 GMT</pubDate>
            <atom:updated>2026-06-12T17:16:55.120Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Deleting Object Properties Can Hurt V8 Performance: Understanding Hidden Classes, Deoptimization, and Dictionary Mode</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NcDMnSYl1Sy49mDZmd8Yg.png" /></figure><p>Most JavaScript developers have used the delete operator countless times.</p><pre>const user = {<br>  name: &quot;John&quot;,<br>  age: 30,<br>  city: &quot;Bangalore&quot;<br>};</pre><pre>delete user.age;</pre><p>Simple, right?</p><p>The property is removed, the application continues to work, and everyone moves on.</p><p>But have you ever wondered what happens inside the JavaScript engine after that line executes?</p><p>As frontend developers, we often focus on writing clean and maintainable code, but understanding how JavaScript engines optimize our code can help us make better decisions — especially in performance-critical applications.</p><p>In this article, we’ll explore how Google’s V8 engine optimizes objects, what Hidden Classes are, why deleting properties can affect performance, and when it actually matters.</p><h3>JavaScript Objects Are Smarter Than You Think</h3><p>Most developers assume JavaScript objects behave like hash maps.</p><p>For example:</p><pre>const user = {<br>  name: &quot;John&quot;,<br>  age: 30,<br>  city: &quot;Bangalore&quot;<br>};</pre><p>It seems reasonable to think that when we access:</p><pre>user.age;</pre><p>JavaScript searches for the key &quot;age&quot; and returns the corresponding value.</p><p>If engines worked this way for every property lookup, JavaScript applications would be much slower.</p><p>Modern engines like V8 use a much more efficient approach.</p><h3>Meet Hidden Classes</h3><p>V8 attempts to optimize JavaScript objects by treating them similarly to structures in lower-level languages.</p><p>When an object is created, V8 generates an internal blueprint known as a Hidden Class.</p><p>Think of a Hidden Class as a map describing where properties are stored in memory.</p><p>For our user object:</p><pre>const user = {<br>  name: &quot;John&quot;,<br>  age: 30,<br>  city: &quot;Bangalore&quot;<br>};</pre><p>V8 internally thinks of it like this:</p><pre>Hidden Class A</pre><pre>Slot 0 → name<br>Slot 1 → age<br>Slot 2 → city</pre><p>Memory might look something like:</p><pre>+-----------+<br>| John      | ← Slot 0<br>+-----------+<br>| 30        | ← Slot 1<br>+-----------+<br>| Bangalore | ← Slot 2<br>+-----------+</pre><p>Now, when JavaScript accesses:</p><pre>user.age</pre><p>V8 doesn’t need to search for &quot;age&quot;.</p><p>It already knows age is located in Slot 1.</p><p>This makes property access incredibly fast.</p><h3>Why Consistent Object Shapes Matter</h3><p>Consider the following objects:</p><pre>const user1 = {<br>  name: &quot;John&quot;,<br>  age: 30,<br>  city: &quot;Bangalore&quot;<br>};</pre><pre>const user2 = {<br>  name: &quot;Jane&quot;,<br>  age: 25,<br>  city: &quot;Mumbai&quot;<br>};</pre><pre>const user3 = {<br>  name: &quot;David&quot;,<br>  age: 40,<br>  city: &quot;Delhi&quot;<br>};</pre><p>All three objects share the same structure.</p><pre>name<br>age<br>city</pre><p>Because the shape is identical, V8 can reuse the same Hidden Class for all of them.</p><p>This allows the engine to generate highly optimized machine code and apply techniques such as Inline Caching.</p><p>The result?</p><p>Faster property access and better runtime performance.</p><h3>The Moment We Delete a Property</h3><p>Now let’s remove a property:</p><pre>delete user1.age;</pre><p>The object becomes:</p><pre>{<br>  name: &quot;John&quot;,<br>  city: &quot;Bangalore&quot;<br>}</pre><p>At first glance, nothing seems unusual.</p><p>However, internally the object’s shape has changed.</p><p>Before deletion:</p><pre>Slot 0 → name<br>Slot 1 → age<br>Slot 2 → city</pre><p>After deletion:</p><pre>Slot 0 → name<br>Slot ? → ?<br>Slot ? → city</pre><p>The Hidden Class V8 was using may no longer be valid.</p><p>The engine must now determine:</p><ul><li>Does the object need a new Hidden Class?</li><li>Can previously optimized code still be used?</li><li>Are existing assumptions still correct?</li></ul><p>This is where performance costs begin to appear.</p><h3>Understanding Deoptimization</h3><p>One of V8’s biggest strengths is its ability to generate optimized machine code based on observed object shapes.</p><p>Suppose a function repeatedly receives objects with the same structure:</p><pre>function getAge(user) {<br>  return user.age;<br>}</pre><p>After enough executions, V8 may optimize the function.</p><p>Internally it might become something similar to:</p><pre>Read Slot 1</pre><p>Extremely fast.</p><p>But once a property is deleted, those assumptions may no longer hold true.</p><p>V8 may need to discard optimized code and return to a slower execution path.</p><p>This process is called <strong>deoptimization</strong>.</p><p>While a single deoptimization is usually insignificant, repeated shape changes can prevent V8 from maintaining its best optimizations.</p><h3>Dictionary Mode: When Flexibility Wins Over Speed</h3><p>If an object undergoes frequent additions and deletions, V8 may eventually abandon its fixed-slot representation altogether.</p><p>Consider:</p><pre>delete obj.a;<br>delete obj.b;<br>obj.c = 1;<br>delete obj.d;<br>obj.e = 2;</pre><p>After enough structural changes, maintaining Hidden Classes becomes inefficient.</p><p>At that point, V8 may switch the object into <strong>Dictionary Mode</strong>.</p><p>Instead of fixed memory slots:</p><pre>Slot 0 → name<br>Slot 1 → age<br>Slot 2 → city</pre><p>the object behaves more like a dynamic lookup table:</p><pre>&quot;name&quot; → John<br>&quot;city&quot; → Bangalore</pre><p>Now property access involves searching for keys rather than directly accessing memory locations.</p><p>This provides flexibility but generally sacrifices performance.</p><h3>Why Setting Undefined Is Different</h3><p>Instead of deleting a property:</p><pre>delete user.age;</pre><p>we can assign:</p><pre>user.age = undefined;</pre><p>The value changes, but the object’s shape remains the same.</p><pre>Slot 0 → name<br>Slot 1 → age<br>Slot 2 → city</pre><p>V8 can continue using the same Hidden Class and preserve many of its optimizations.</p><p>This is why developers sometimes recommend using undefined in performance-sensitive code paths.</p><h3>Should You Stop Using Delete?</h3><p>Absolutely not.</p><p>One of the biggest misconceptions in JavaScript performance discussions is that delete should never be used.</p><p>That’s not true.</p><h3>Use delete when:</h3><pre>delete payload.debugInfo;<br>delete request.internalMetadata;<br>delete response.tempData;</pre><p>The property genuinely shouldn’t exist anymore.</p><p>These operations usually occur infrequently and have negligible performance impact.</p><h3>Be careful when:</h3><pre>for (let i = 0; i &lt; 1000000; i++) {<br>  delete users[i].cache;<br>}</pre><p>or inside rendering loops, data processing pipelines, or high-throughput server code.</p><p>Repeated shape changes can interfere with V8’s optimization strategies.</p><h3>The Real Lesson</h3><p>The performance concern isn’t that deleting a property is expensive.</p><p>The real concern is what happens afterward.</p><pre>Delete Property<br>        ↓<br>Object Shape Changes<br>        ↓<br>Hidden Class Changes<br>        ↓<br>Optimization Assumptions Break<br>        ↓<br>Potential Deoptimization<br>        ↓<br>Possible Dictionary Mode<br>        ↓<br>Slower Property Access</pre><p>Understanding this chain of events gives developers a deeper appreciation of how JavaScript engines work under the hood.</p><h3>Summary</h3><p>Most applications will never experience noticeable performance issues from a few delete statements.</p><p>Readability and correctness should always come first.</p><p>However, understanding Hidden Classes, object shapes, deoptimization, and dictionary mode provides valuable insight into how modern JavaScript engines optimize our code.</p><p>As developers, we write JavaScript every day.</p><p>The more we understand what happens behind the scenes, the better equipped we are to write efficient, predictable, and scalable applications.</p><p>Sometimes, the most interesting performance lessons come from a single line of code:</p><pre>delete user.age;</pre><p>A simple statement with far more happening behind the scenes than most developers realize.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93f3bfd7de01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL Explained for React Developers: What Makes It Different from REST?]]></title>
            <link>https://medium.com/@manappa.kammar777/graphql-explained-for-react-developers-what-makes-it-different-from-rest-adcce6dc646d?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/adcce6dc646d</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-apollo-server]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 16:37:05 GMT</pubDate>
            <atom:updated>2026-06-09T16:21:42.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZXUKRzVi_AS9d8JAVVyKw.png" /></figure><h3>Introduction</h3><p>One of the most common questions developers ask when learning GraphQL is:</p><blockquote><em>“If GraphQL still makes HTTP requests just like REST APIs, what actually makes it different?”</em></blockquote><p>When you open Chrome DevTools and inspect the Network tab, both REST and GraphQL appear to do the same thing:</p><ul><li>Send requests over HTTP</li><li>Receive JSON responses</li><li>Communicate with backend services</li></ul><p>So why was GraphQL created, and why do companies use it?</p><p>This article explores GraphQL from a practical React developer’s perspective and uses a real Apollo Server example to explain the concepts.</p><h3>REST vs GraphQL: The Fundamental Difference</h3><p>Many developers initially believe GraphQL’s biggest advantage is reducing network calls.</p><p>In reality, that is not the primary benefit.</p><p>The real difference is:</p><h3>REST is Resource-Driven</h3><p>REST focuses on endpoints:</p><pre>/users<br>/posts<br>/comments<br>/orders</pre><p>The server decides:</p><ul><li>What endpoints exist</li><li>What data each endpoint returns</li><li>The structure of the response</li></ul><p>The frontend consumes whatever the backend provides.</p><h3>GraphQL is Data-Driven</h3><p>GraphQL typically exposes a single endpoint:</p><pre>/graphql</pre><p>Instead of asking for resources, the client asks for exactly the data it needs.</p><p>Example:</p><pre>query {<br>  user(id: 1) {<br>    name<br>    username<br>  }<br>}</pre><p>Response:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;user&quot;: {<br>      &quot;name&quot;: &quot;John&quot;,<br>      &quot;username&quot;: &quot;john&quot;<br>    }<br>  }<br>}</pre><p>The client controls the response shape.</p><h3>Does GraphQL Reduce Network Calls?</h3><p>Not always.</p><p>This is one of the biggest misconceptions about GraphQL.</p><p>For example, a REST endpoint could return:</p><pre>GET /product-page/1</pre><p>and include:</p><ul><li>Product</li><li>Reviews</li><li>Inventory</li><li>Seller Information</li></ul><p>in a single response.</p><p>That is already one network call.</p><p>GraphQL can achieve the same thing.</p><p>The real advantage is not fewer requests.</p><p>The real advantage is:</p><blockquote><em>The frontend can request exactly what it needs without requiring new endpoints.</em></blockquote><h3>Understanding GraphQL Through a Real Apollo Server Example</h3><p>Imagine we have a GraphQL API with:</p><h3>Users</h3><pre>const UserList = [<br>  {<br>    id: 1,<br>    name: &quot;John&quot;,<br>    username: &quot;john&quot;,<br>    age: 20<br>  }<br>];</pre><h3>Movies</h3><pre>const MovieList = [<br>  {<br>    id: 1,<br>    name: &quot;Avengers Endgame&quot;<br>  }<br>];</pre><p>Apollo Server connects:</p><pre>const server = new ApolloServer({<br>  typeDefs,<br>  resolvers<br>});</pre><p>Now let’s understand the core concepts.</p><h3>1. Basic Types and Queries</h3><p>Types define the shape of data.</p><p>Example:</p><pre>type User {<br>  id: ID!<br>  name: String!<br>  username: String!<br>  age: Int!<br>}</pre><p>This tells GraphQL:</p><pre>Every User contains:<br>- id<br>- name<br>- username<br>- age</pre><p>Queries define what data can be requested.</p><p>Example:</p><pre>type Query {<br>  users: [User!]!<br>  user(id: ID!): User!<br>}</pre><p>Now clients can execute:</p><pre>query {<br>  users {<br>    name<br>    age<br>  }<br>}</pre><p>GraphQL returns only those fields.</p><p>This is one of the biggest differences from traditional REST APIs.</p><h3>2. GraphQL API Using Node.js</h3><p>Node.js hosts the GraphQL server.</p><p>Apollo Server acts as the GraphQL engine.</p><p>Example:</p><pre>const server = new ApolloServer({<br>  typeDefs,<br>  resolvers<br>});</pre><p>Responsibilities:</p><ul><li>Accept GraphQL requests</li><li>Validate queries</li><li>Execute resolvers</li><li>Return responses</li></ul><p>Think of Apollo Server as Express.js specifically designed for GraphQL.</p><h3>3. GraphQL Resolvers</h3><p>Resolvers contain the actual logic.</p><p>The schema defines:</p><blockquote><em>What can be requested.</em></blockquote><p>Resolvers define:</p><blockquote><em>How the data is retrieved.</em></blockquote><p>Example:</p><pre>users: () =&gt; {<br>  return UserList;<br>}</pre><p>When the client executes:</p><pre>query {<br>  users {<br>    name<br>  }<br>}</pre><p>GraphQL calls the resolver:</p><pre>users()</pre><p>and returns data.</p><p>Another example:</p><pre>user: (parent, args) =&gt; {<br>  return _.find(UserList, {<br>    id: Number(args.id)<br>  });<br>}</pre><p>The resolver receives arguments and returns the matching user.</p><p>Without resolvers, GraphQL would know the data structure but would not know where the data comes from.</p><h3>4. Mutations</h3><p>Queries read data.</p><p>Mutations modify data.</p><p>Example schema:</p><pre>type Mutation {<br>  createUser(<br>    input: CreateUserInput!<br>  ): User<br>}</pre><p>Example mutation:</p><pre>mutation {<br>  createUser(<br>    input: {<br>      name: &quot;Mike&quot;<br>      username: &quot;mike&quot;<br>      age: 30<br>    }<br>  ) {<br>    id<br>    name<br>  }<br>}</pre><p>Resolver:</p><pre>createUser(parent, args) {<br>  UserList.push(args.input);<br>  return args.input;<br>}</pre><p>Mutations are GraphQL’s solution for:</p><ul><li>Create</li><li>Update</li><li>Delete</li></ul><p>operations.</p><h3>5. GraphQL in React — useQuery</h3><p>React applications consume GraphQL through Apollo Client.</p><p>Example:</p><pre>const { loading, error, data } =<br>  useQuery(GET_USERS);</pre><p>The hook:</p><ul><li>Sends a GraphQL query</li><li>Manages loading states</li><li>Handles errors</li><li>Stores results</li><li>Updates the UI automatically</li></ul><p>Flow:</p><pre>React Component<br>       ↓<br>useQuery<br>       ↓<br>Apollo Client<br>       ↓<br>GraphQL Server<br>       ↓<br>Resolver<br>       ↓<br>Data Returned</pre><p>This removes much of the manual state management typically required with REST APIs.</p><h3>6. GraphQL in React — useMutation</h3><p>For updates and actions, React uses:</p><pre>const [createUser] =<br>  useMutation(CREATE_USER);</pre><p>Example:</p><pre>createUser({<br>  variables: {<br>    input: {<br>      name: &quot;Mike&quot;,<br>      username: &quot;mike&quot;,<br>      age: 30<br>    }<br>  }<br>});</pre><p>This sends a GraphQL mutation to the server.</p><p>The server executes the mutation resolver and returns the result.</p><p>Think of useMutation as the action layer of GraphQL.</p><h3>7. Context</h3><p>Context provides shared information across all resolvers.</p><p>Example:</p><pre>context: ({ req }) =&gt; {<br>  return {<br>    user: req.user<br>  };<br>}</pre><p>Now every resolver can access:</p><pre>context.user</pre><p>Common uses:</p><ul><li>Authentication</li><li>Authorization</li><li>Database connections</li><li>Request metadata</li><li>Multi-tenant systems</li></ul><p>Context acts as a shared request container.</p><h3>8. Fragments</h3><p>As applications grow, field selections become repetitive.</p><p>Without fragments:</p><pre>query {<br>  users {<br>    id<br>    name<br>    username<br>  }</pre><pre>  user(id: 1) {<br>    id<br>    name<br>    username<br>  }<br>}</pre><p>The same fields appear multiple times.</p><p>Fragments solve this.</p><p>Example:</p><pre>fragment UserFields on User {<br>  id<br>  name<br>  username<br>}</pre><p>Usage:</p><pre>query {<br>  users {<br>    ...UserFields<br>  }</pre><pre>  user(id: 1) {<br>    ...UserFields<br>  }<br>}</pre><p>Benefits:</p><ul><li>Reusability</li><li>Cleaner queries</li><li>Easier maintenance</li></ul><p>Think of fragments as reusable templates.</p><h3>9. Unions</h3><p>Normally GraphQL fields return one type.</p><p>Example:</p><pre>user(id: 1): User</pre><p>However, some features return multiple possible types.</p><p>Examples:</p><ul><li>Search</li><li>Notifications</li><li>Activity Feeds</li></ul><p>GraphQL supports this through Unions.</p><p>Example:</p><pre>union SearchResult =<br>  User | Movie</pre><p>Now a search operation can return:</p><pre>User Results<br>Movie Results</pre><p>within the same response.</p><p>This allows GraphQL to model real-world scenarios more effectively.</p><h3>Why Large Companies Adopt GraphQL</h3><p>Large organizations often have:</p><ul><li>Multiple frontend teams</li><li>Web applications</li><li>Mobile applications</li><li>Numerous backend services</li></ul><p>Without GraphQL:</p><pre>Frontend Team<br>    ↓<br>Request New Endpoint<br>    ↓<br>Backend Team<br>    ↓<br>Create API</pre><p>With GraphQL:</p><pre>Frontend Team<br>    ↓<br>Request Additional Fields<br>    ↓<br>Done</pre><p>The schema becomes the contract.</p><p>The frontend becomes more independent.</p><h3>The Most Important Takeaway</h3><p>GraphQL’s greatest strength is not reducing HTTP requests.</p><p>Its greatest strength is giving the client control over the shape of the data.</p><p>REST asks:</p><blockquote><em>Which endpoint should I call?</em></blockquote><p>GraphQL asks:</p><blockquote><em>What data do I need?</em></blockquote><p>That shift in mindset is what makes GraphQL fundamentally different.</p><h3>Final Thoughts</h3><p>GraphQL is not a replacement for REST.</p><p>In fact, many GraphQL servers internally call REST APIs.</p><p>The real value of GraphQL lies in:</p><ul><li>Flexible data fetching</li><li>Strong typing</li><li>Better developer experience</li><li>Reduced frontend-backend dependency</li><li>Easier API evolution</li></ul><blockquote><em>REST is resource-driven. GraphQL is data-driven. The client controls the response shape, and that changes how frontend and backend teams collaborate.</em></blockquote><p>GitHub Repo:- <a href="https://github.com/Manappak/graphQl">https://github.com/Manappak/graphQl</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adcce6dc646d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Memory Leaks in Single Page Applications: A Frontend Engineer’s Guide]]></title>
            <link>https://medium.com/@manappa.kammar777/understanding-memory-leaks-in-single-page-applications-a-frontend-engineers-guide-07a72f8798ed?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/07a72f8798ed</guid>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 17:04:51 GMT</pubDate>
            <atom:updated>2026-06-01T17:07:57.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIyFJfVY-O1ifkvEBmwivg.jpeg" /></figure><p>Modern frontend applications have become increasingly sophisticated. Frameworks like React, Angular, and Vue allow us to build rich user experiences without constantly refreshing the page.</p><p>While this architecture provides a seamless experience for users, it also introduces a unique challenge: <strong>memory leaks</strong>.</p><p>Memory leaks are one of the most common causes of performance degradation in Single Page Applications (SPAs). They often go unnoticed during development but become painfully obvious in production when users keep an application open for hours.</p><p>In this article, we’ll explore:</p><ul><li>What memory leaks are</li><li>How JavaScript Garbage Collection works</li><li>Why memory leaks happen in SPAs</li><li>Real-world examples involving Event Listeners, Timers, WebSockets, Fetch Requests, and Detached DOM Nodes</li><li>How to debug memory leaks using Chrome DevTools</li></ul><p>Let’s dive in.</p><h3>What Is a Memory Leak?</h3><p>A memory leak occurs when memory that is no longer needed remains referenced somewhere in the application, preventing JavaScript’s Garbage Collector from reclaiming it.</p><p>Many developers assume memory leaks happen because an object is large.</p><p>That’s not true.</p><p>The real issue is that the object is still reachable.</p><p>Consider the following example:</p><pre>let user = {<br>  name: &quot;John&quot;<br>};</pre><pre>user = null;</pre><p>Since no references remain, the Garbage Collector can safely remove the object from memory.</p><p>Now consider:</p><pre>const cache = [];</pre><pre>let user = {<br>  name: &quot;John&quot;<br>};</pre><pre>cache.push(user);</pre><pre>user = null;</pre><p>Even though user is now null, the object still exists because the cache array maintains a reference to it.</p><p>This principle is the foundation of every memory leak you’ll encounter.</p><h3>How JavaScript Garbage Collection Works</h3><p>JavaScript uses an automatic memory management system called Garbage Collection.</p><p>The Garbage Collector periodically checks which objects are still reachable.</p><p>If an object cannot be reached through any chain of references, it becomes eligible for cleanup.</p><p>Think of it like this:</p><pre>Reachable = Stays in Memory</pre><pre>Unreachable = Removed by Garbage Collector</pre><p>Memory leaks occur when we accidentally keep objects reachable long after they’re needed.</p><h3>Why SPAs Are More Vulnerable to Memory Leaks</h3><p>Traditional multi-page applications refresh the browser page during navigation.</p><p>This means:</p><ul><li>JavaScript execution restarts</li><li>Memory is reset</li><li>Unused resources are naturally cleaned up</li></ul><p>Single Page Applications behave differently.</p><p>The application remains loaded while users navigate between routes.</p><p>As users interact with the application:</p><ul><li>Components mount and unmount</li><li>Event listeners are attached</li><li>Timers are created</li><li>API requests are made</li><li>WebSocket connections stay active</li></ul><p>If these resources aren’t cleaned up correctly, memory usage continuously grows.</p><h3>Memory Leak Example #1: Event Listeners</h3><p>One of the most common memory leaks involves event listeners.</p><pre>useEffect(() =&gt; {<br>  window.addEventListener(&quot;resize&quot;, handleResize);<br>}, []);</pre><p>At first glance, this appears harmless.</p><p>However, the browser stores a reference to the callback.</p><p>Internally, it looks something like this:</p><pre>Window<br> └── resize listener<br>      └── handleResize</pre><p>Now consider this component:</p><pre>function Dashboard() {<br>  const largeData = new Array(100000);</pre><pre>  function handleResize() {<br>    console.log(largeData.length);<br>  }</pre><pre>  useEffect(() =&gt; {<br>    window.addEventListener(&quot;resize&quot;, handleResize);<br>  }, []);</pre><pre>  return &lt;div&gt;Dashboard&lt;/div&gt;;<br>}</pre><p>The callback is a closure.</p><p>Closures remember variables from their surrounding scope.</p><p>This means:</p><pre>Window<br> └── resize listener<br>      └── handleResize<br>           └── largeData</pre><p>Even after the component unmounts, the event listener still exists.</p><p>Since the listener references handleResize, and handleResize references largeData, none of that memory can be reclaimed.</p><h3>The Fix</h3><pre>useEffect(() =&gt; {<br>  window.addEventListener(&quot;resize&quot;, handleResize);</pre><pre>  return () =&gt; {<br>    window.removeEventListener(&quot;resize&quot;, handleResize);<br>  };<br>}, []);</pre><p>Always clean up event listeners when a component unmounts.</p><h3>Memory Leak Example #2: setInterval</h3><p>Timers are another frequent source of memory leaks.</p><pre>setInterval(() =&gt; {<br>  console.log(&quot;running&quot;);<br>}, 1000);</pre><p>When this code executes, the browser stores the callback in its timer registry.</p><pre>Timer Registry<br> └── callback</pre><p>Now imagine:</p><pre>function Dashboard() {<br>  const data = new Array(100000);</pre><pre>  useEffect(() =&gt; {<br>    setInterval(() =&gt; {<br>      console.log(data.length);<br>    }, 1000);<br>  }, []);<br>}</pre><p>Internally:</p><pre>Timer<br> └── callback<br>      └── closure<br>           └── data</pre><p>The timer continues running even after the component disappears.</p><p>The callback retains access to data, preventing it from being garbage collected.</p><h3>The Fix</h3><pre>useEffect(() =&gt; {<br>  const id = setInterval(() =&gt; {<br>    console.log(&quot;running&quot;);<br>  }, 1000);</pre><pre>  return () =&gt; clearInterval(id);<br>}, []);</pre><p>Always clear intervals when they are no longer needed.</p><h3>Memory Leak Example #3: WebSockets</h3><p>WebSockets are designed to maintain long-lived connections.</p><pre>const socket = new WebSocket(url);</pre><p>Internally:</p><pre>Socket Connection<br> ├── Network Connection<br> ├── Event Handlers<br> └── Message Queue</pre><p>A typical React implementation might look like this:</p><pre>useEffect(() =&gt; {<br>  const socket = new WebSocket(url);</pre><pre>  socket.onmessage = (message) =&gt; {<br>    setMessages(prev =&gt; [...prev, message.data]);<br>  };<br>}, []);</pre><p>The socket maintains references to event handlers and component state.</p><p>If the component unmounts but the socket remains connected, messages continue arriving.</p><p>Over time:</p><ul><li>Memory usage increases</li><li>State updates continue</li><li>Network activity persists</li></ul><h3>The Fix</h3><pre>useEffect(() =&gt; {<br>  const socket = new WebSocket(url);</pre><pre>  return () =&gt; {<br>    socket.close();<br>  };<br>}, []);</pre><p>Always close WebSocket connections when they are no longer needed.</p><h3>Memory Leak Example #4: Pending Fetch Requests</h3><p>Not every fetch request causes a memory leak.</p><p>However, pending requests can temporarily retain component memory.</p><pre>fetch(&quot;/api/data&quot;)<br>  .then(setData);</pre><p>Internally:</p><pre>Fetch Request<br> └── Promise<br>      └── callback<br>           └── component scope</pre><p>Imagine this timeline:</p><pre>Component Mounts<br>      ↓<br>Fetch Starts<br>      ↓<br>User Navigates Away<br>      ↓<br>Response Arrives</pre><p>Until the request completes, the Promise chain retains references to the callback and surrounding scope.</p><h3>The Fix</h3><pre>useEffect(() =&gt; {<br>  const controller = new AbortController();</pre><pre>  fetch(&quot;/api/data&quot;, {<br>    signal: controller.signal<br>  });</pre><pre>  return () =&gt; controller.abort();<br>}, []);</pre><p>Aborting unnecessary requests helps release resources earlier and prevents unwanted updates.</p><h3>Memory Leak Example #5: Detached DOM Nodes</h3><p>Detached DOM Nodes are one of the most interesting and often overlooked memory leaks.</p><p>Consider:</p><pre>const cache = [];</pre><pre>function create() {<br>  const div = document.createElement(&quot;div&quot;);<br>  cache.push(div);<br>}</pre><p>Every call stores another DOM node in memory.</p><p>Now imagine:</p><pre>const modal = document.createElement(&quot;div&quot;);</pre><pre>document.body.appendChild(modal);</pre><pre>cache.push(modal);</pre><pre>document.body.removeChild(modal);</pre><p>The modal is removed from the page but still exists in memory because cache maintains a reference.</p><pre>cache<br> └── modal</pre><p>This creates a Detached DOM Node.</p><p>In Chrome DevTools, you’ll often see:</p><pre>Detached HTMLDivElement<br>Detached HTMLButtonElement<br>Detached HTMLSpanElement</pre><p>These entries are strong indicators of memory leaks.</p><h3>How to Debug Memory Leaks</h3><h3>1. Use Heap Snapshots</h3><p>Open:</p><pre>Chrome DevTools<br>→ Memory</pre><p>Take a Heap Snapshot before and after reproducing the issue.</p><p>Compare memory growth.</p><h3>2. Look for Detached DOM Nodes</h3><p>Search for:</p><pre>Detached HTMLDivElement<br>Detached HTMLElement</pre><p>These are frequently the source of memory retention.</p><h3>3. Monitor Memory Usage</h3><p>Open:</p><pre>DevTools<br>→ More Tools<br>→ Performance Monitor</pre><p>Watch:</p><ul><li>JS Heap Size</li><li>DOM Node Count</li><li>Event Listener Count</li></ul><p>If these numbers continuously increase, investigate further.</p><h3>4. Force Garbage Collection</h3><p>Use the “Collect Garbage” button in the Memory panel.</p><p>If memory remains high after garbage collection, some reference is still keeping objects alive.</p><h3>5. Inspect Retainers</h3><p>This is the most powerful debugging technique.</p><p>Chrome shows exactly what is retaining an object:</p><pre>Window<br> └── EventListener<br>      └── Function<br>           └── Closure</pre><p>The Retainers panel answers the most important question:</p><p><strong>What is preventing this object from being garbage collected?</strong></p><h3>Final Thoughts</h3><p>Memory leaks are rarely caused by a single massive object.</p><p>More often, they are caused by small references that accumulate over time.</p><p>The most common sources are:</p><ul><li>Event Listeners</li><li>Timers</li><li>WebSockets</li><li>Observers</li><li>Promises</li><li>Detached DOM Nodes</li><li>Global Caches</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07a72f8798ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JavaScript Event Loop, Call Stack, Microtasks & Macrotasks — Step by Step]]></title>
            <link>https://medium.com/@manappa.kammar777/understanding-javascript-event-loop-call-stack-microtasks-macrotasks-step-by-step-8d7a3582ba3c?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d7a3582ba3c</guid>
            <category><![CDATA[micro-tasks]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[macrotask]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Wed, 13 May 2026 12:25:59 GMT</pubDate>
            <atom:updated>2026-05-13T12:25:59.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*XVqPA2z1dTHJWm2TwIAsBw.gif" /></figure><p>One of the most confusing topics in JavaScript is:</p><ul><li>Call Stack</li><li>Event Loop</li><li>Microtasks</li><li>Macrotasks</li><li>Promises</li><li>setTimeout</li></ul><p>Most developers memorize:</p><pre>Promise &gt; setTimeout</pre><p>But they still do not truly understand:</p><ul><li>Why does it happen?</li><li>Who executes first?</li><li>When does the Event Loop actually run?</li><li>Does JavaScript jump between tasks?</li><li>How does the browser display values one after another?</li></ul><p>This article explains everything visually and step by step.</p><h3>The Example We’ll Use</h3><pre>console.log(&quot;1&quot;);<br><br>setTimeout(() =&gt; console.log(&quot;2&quot;));<br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;3&quot;);<br>setTimeout(() =&gt; console.log(&quot;4&quot;));<br>Promise.resolve().then(() =&gt; {<br>    console.log(&quot;5&quot;);<br>  });<br>});<br>console.log(&quot;6&quot;);</pre><h3>Final Output</h3><pre>1<br>6<br>3<br>5<br>2<br>4</pre><p>Now let’s understand exactly HOW JavaScript reaches this output.</p><h3>First Important Truth</h3><p>JavaScript is: Single Threaded</p><p>That means: JavaScript executes ONE thing at a time.</p><p>It cannot execute:</p><ul><li>two functions together</li><li>two console.logs together</li><li>two loops together</li></ul><p>Everything runs sequentially.</p><h3>JavaScript Runtime Architecture</h3><p>When JavaScript runs inside the browser, multiple systems work together.</p><pre>┌─────────────────────┐<br>│     Browser         │<br>│─────────────────────│<br>│ Web APIs            │<br>│ Event Loop          │<br>│ Callback Queues     │<br>└─────────────────────┘<br>          ▲<br>          │<br>          ▼<br>┌─────────────────────┐<br>│ JavaScript Engine   │<br>│─────────────────────│<br>│ Memory Heap         │<br>│ Call Stack          │<br>└─────────────────────┘</pre><h3>The Main Components</h3><h3>1. Call Stack</h3><p>The Call Stack executes synchronous code.</p><p>Example:</p><pre>console.log(&quot;Hello&quot;)</pre><p>The function enters the stack, executes, and leaves.</p><h3>2. Web APIs</h3><p>The browser provides APIs like:</p><ul><li>setTimeout</li><li>DOM events</li><li>fetch</li><li>timers</li></ul><p>These are handled outside JavaScript.</p><h3>3. Microtask Queue</h3><p>High-priority queue.</p><p>Contains:</p><ul><li>Promise.then</li><li>Promise.catch</li><li>Promise.finally</li><li>queueMicrotask</li></ul><h3>4. Macrotask Queue</h3><p>Normal-priority queue.</p><p>Contains:</p><ul><li>setTimeout</li><li>setInterval</li><li>DOM events</li></ul><h3>5. Event Loop</h3><p>The Event Loop continuously checks: <em>Is the Call Stack empty?</em></p><p>If YES:</p><ul><li>execute all microtasks</li><li>then execute one macrotask</li></ul><h3>Most Important Rule</h3><pre>Synchronous Code<br>        ↓<br>ALL Microtasks<br>        ↓<br>ONE Macrotask<br>        ↓<br>Repeat</pre><p>This single rule explains almost everything.</p><h3>Initial State</h3><p>Before code execution:</p><pre>CALL STACK<br>(empty)<br><br>MICROTASK QUEUE<br>(empty)<br><br>MACROTASK QUEUE<br>(empty)</pre><h3>Browser Loads the Script</h3><p>The browser tells JavaScript:</p><pre>Execute this file</pre><p>The entire script enters the Call Stack.</p><pre>CALL STACK<br>------------<br>Global Execution Context</pre><p>Now JavaScript starts executing line by line.</p><h3>Step 1</h3><pre>console.log(&quot;1&quot;);</pre><p>Call Stack:</p><pre>CALL STACK<br>------------<br>console.log<br>Global()</pre><p>JavaScript executes console.log.</p><p>Browser console displays:</p><pre>1</pre><p>Then console.log is removed from the stack.</p><p>Current state:</p><pre>CALL STACK<br>------------<br>Global()</pre><h3>Important Observation</h3><p>At this moment: Event Loop does NOTHING.</p><p>Why?</p><p>Because: Call Stack is NOT empty.</p><p>The Global Execution Context is still running.</p><h3>Step 2</h3><pre>setTimeout(() =&gt; console.log(&quot;2&quot;));</pre><p>Call Stack:</p><pre>CALL STACK<br>------------<br>setTimeout<br>Global()</pre><p>JavaScript sees async work.</p><p>The browser handles the timer using Web APIs.</p><p>The callback:</p><pre>() =&gt; console.log(&quot;2&quot;)</pre><p>is stored temporarily outside JavaScript.</p><p>After timer completion:</p><p>The callback moves into: MACROTASK QUEUE</p><p>Current state:</p><pre>CALL STACK<br>------------<br>Global()<br><br>MICROTASK QUEUE<br>(empty)<br><br>MACROTASK QUEUE<br>----------------<br>console.log(&quot;2&quot;)</pre><h3>Step 3</h3><pre>Promise.resolve().then(...)</pre><p>Promises are different.</p><p>Their callbacks go into:</p><pre>MICROTASK QUEUE</pre><p>Current state:</p><pre>CALL STACK<br>------------<br>Global()<br><br>MICROTASK QUEUE<br>----------------<br>Promise callback<br><br>MACROTASK QUEUE<br>----------------<br>console.log(&quot;2&quot;)</pre><h3>Step 4</h3><pre>console.log(&quot;6&quot;)</pre><p>Call Stack:</p><pre>CALL STACK<br>------------<br>console.log<br>Global()</pre><p>Output:</p><pre>6</pre><p>console.log leaves the stack.</p><h3>Huge Moment</h3><p>Now the entire file has finished executing.</p><p>The Global Execution Context leaves the stack.</p><p>Now:</p><pre>CALL STACK<br>(empty)</pre><p>Only NOW does the Event Loop start working.</p><h3>Important Understanding</h3><p>JavaScript does NOT:</p><pre>Run one line<br>Go to event loop<br>Come back<br>Run next line</pre><p>That is NOT how it works.</p><p>Instead: JavaScript finishes ALL synchronous code first.</p><p>Only after the stack becomes empty: The Event Loop starts checking queues.</p><h3>Event Loop Starts</h3><p>The Event Loop checks:</p><pre>Is Call Stack empty?<br>YES</pre><p>Then:</p><pre>Are there microtasks?<br>YES</pre><p>Microtasks have higher priority.</p><h3>Step 5 — Promise Callback Executes</h3><p>The Promise callback moves into the Call Stack.</p><pre>CALL STACK<br>------------<br>Promise callback</pre><p>Now the callback executes.</p><h3>Step 5A</h3><pre>console.log(&quot;3&quot;)</pre><p>Output:</p><pre>3</pre><h3>Step 5B</h3><pre>setTimeout(() =&gt; console.log(&quot;4&quot;))</pre><p>This callback moves into:</p><pre>MACROTASK QUEUE</pre><p>Current state:</p><pre>MACROTASK QUEUE<br>----------------<br>console.log(&quot;2&quot;)<br>console.log(&quot;4&quot;)</pre><h3>Step 5C</h3><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;5&quot;)<br>})</pre><p>This creates another microtask.</p><p>Current state:</p><pre>MICROTASK QUEUE<br>----------------<br>console.log(&quot;5&quot;)</pre><p>The Promise callback finishes.</p><p>Call Stack becomes empty again.</p><h3>Event Loop Runs Again</h3><p>The Event Loop checks:</p><pre>Microtasks available?<br>YES</pre><p>Important rule:</p><pre>Before executing any macrotask,<br>JavaScript empties ALL microtasks.</pre><h3>Step 6 — Execute Microtask</h3><pre>console.log(&quot;5&quot;)</pre><p>Output:</p><pre>5</pre><p>Now:</p><pre>MICROTASK QUEUE<br>(empty)</pre><h3>Step 7 — Execute First Macrotask</h3><p>Now the Event Loop checks:</p><pre>Microtasks empty?<br>YES</pre><p>Take ONE macrotask.</p><pre>console.log(&quot;2&quot;)</pre><p>Output:</p><pre>2</pre><h3>Step 8 — Execute Next Macrotask</h3><pre>console.log(&quot;4&quot;)</pre><p>Output:</p><pre>4</pre><h3>Final Output Again</h3><pre>1<br>6<br>3<br>5<br>2<br>4</pre><h3>Full Timeline Visualization</h3><pre>GLOBAL EXECUTION STARTS<br>--------------------------------<br>print 1<br>register timeout 2<br>queue promise callback<br>print 6<br>GLOBAL EXECUTION ENDS<br><br>EVENT LOOP STARTS<br>--------------------------------<br>run promise callback<br>    print 3<br>    register timeout 4<br>    queue promise 5<br><br>run promise 5<br>    print 5<br><br>run timeout 2<br>    print 2<br><br>run timeout 4<br>    print 4</pre><h3>Visual Queue Flow</h3><pre>                Browser<br>                   |<br>                   v    <br>        ┌────────────────┐<br>        │   CALL STACK   │<br>        └────────────────┘<br>                   |<br>                   v<br>         Synchronous Code Runs<br>                   |<br>                   v<br>         Stack Becomes Empty<br>                   |<br>                   v<br>        ┌────────────────┐<br>        │   EVENT LOOP   │<br>        └────────────────┘<br>             /        \<br>            v          v<br>┌────────────────┐  ┌────────────────┐<br>│ MICROTASK QUEUE│  │ MACROTASK QUEUE│<br>└────────────────┘  └────────────────┘</pre><h3>Why Promises Execute Before setTimeout</h3><p>Because:</p><pre>Promises = Microtasks<br>setTimeout = Macrotasks</pre><p>And JavaScript always executes:</p><pre>ALL microtasks BEFORE macrotasks.</pre><h3>Important Realization</h3><p>JavaScript never pauses synchronous execution to run async callbacks.</p><p>Callbacks only execute when:</p><pre>Call Stack becomes empty.</pre><p>This is the heart of the Event Loop.</p><h3>Common Interview Question</h3><pre>setTimeout(() =&gt; console.log(&quot;timeout&quot;));<br>Promise.resolve().then(() =&gt; console.log(&quot;promise&quot;));<br>console.log(&quot;sync&quot;);</pre><p>Output:</p><pre>sync<br>promise<br>timeout</pre><p>Why?</p><pre>Sync code first<br>Then microtasks<br>Then macrotasks</pre><h3>The Biggest Misunderstanding</h3><p>Many developers think:</p><pre>Event Loop runs after every line.</pre><p>Wrong.</p><p>The Event Loop only gets a chance when:</p><pre>Call Stack becomes empty.</pre><p>That is extremely important.</p><h3>Easy Memory Trick</h3><p>Think of task priority like this:</p><pre>Synchronous Code = Do immediately<br>Microtasks = VIP queue<br>Macrotasks = Normal queue</pre><p>Execution order:</p><pre>Sync → VIP → Normal</pre><h3>Real Browser Rendering Behavior</h3><p>Another important concept:</p><pre>JavaScript blocks rendering.</pre><p>While JavaScript is running:</p><ul><li>browser cannot repaint</li><li>UI may freeze</li><li>clicks may wait</li></ul><p>Example:</p><pre>while(true) {}</pre><p>This blocks:</p><ul><li>rendering</li><li>event loop</li><li>browser interactions</li></ul><p>because the Call Stack never becomes empty.</p><h3>Ultimate Mental Model</h3><pre>1. Execute synchronous code completely<br>2. Stack becomes empty<br>3. Execute ALL microtasks<br>4. Execute ONE macrotask<br>5. Repeat forever</pre><p>If you understand this flow clearly, the JavaScript Event Loop becomes much easier to reason about.</p><h3>One Line That Explains Everything</h3><pre>Before executing any macrotask,<br>JavaScript empties the entire microtask queue.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d7a3582ba3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to Use useQuery in React — And Why It’s Better Than useEffect for Data Fetching]]></title>
            <link>https://medium.com/@manappa.kammar777/when-to-use-usequery-in-react-and-why-its-better-than-useeffect-for-data-fetching-eecd7dd54986?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/eecd7dd54986</guid>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 11:47:06 GMT</pubDate>
            <atom:updated>2026-02-02T11:47:06.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>When to Use useQuery in React — And Why It’s Better Than useEffect for Data Fetching</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*_fl4wRRjz-Uy6wJ1dNd35A.jpeg" /></figure><p>As React developers, we fetch data all the time — from REST APIs, GraphQL endpoints, or backend services. For years, the go-to pattern was using useEffect combined with useState to manage network requests. But as apps grow in complexity, that pattern starts showing its limitations.</p><h3>What is useQuery?</h3><p>useQuery is a hook provided by libraries like TanStack React Query. It is designed specifically for managing server state.</p><p>useQuery is a hook that helps with:</p><ul><li>Fetching and caching server data</li><li>Managing loading and error states</li><li>Synchronising data across components</li><li>Refetching data on an interval or network changes</li></ul><blockquote><em>Unlike a plain </em><em>useEffect, It’s designed for server state — not local UI state.</em></blockquote><h3>Why useQuery Beats useEffect for Data Fetching:-</h3><p>When you use useEffect for API calls, you typically write a pattern like this:</p><pre>const [data, setData] = useState(null);<br>const [loading, setLoading] = useState(true);<br>const [error, setError] = useState(null);</pre><pre>useEffect(() =&gt; {<br>  fetch(url)<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; setData(data))<br>    .catch(err =&gt; setError(err))<br>    .finally(() =&gt; setLoading(false));<br>}, [url]);</pre><p>This works — but:</p><ul><li>You must manually track loading and error states</li><li>No built-in caching</li><li>No background refetching</li><li>Duplicate requests are easy</li></ul><p>With useQuery, This becomes almost zero-boilerplate:</p><pre>const { data, isLoading, error } = useQuery({<br>  queryKey: [&#39;users&#39;],<br>  queryFn: fetchUsers<br>});</pre><h3>When to Use useQuery:-</h3><p><strong>Your app needs to fetch server data:- </strong>Any GET requests that display dynamic content.</p><p>Examples:</p><ul><li>Fetching lists (products, posts, users)</li><li>User profile data</li><li>Dashboard statistics</li></ul><p><strong>Data is shared in more than one component:- </strong>Instead of fetching the same API in multiple places, useQuery caches it and shares it automatically.</p><p><strong>You want automatic caching and deduplication:- </strong>If two components mount at the same time, only one network call is made.</p><p><strong>You want background refresh &amp; stale-while-revalidate:- </strong>React Query refetches on focus, reconnect, or on a timer, keeping UI data fresh.</p><h3>When Not to Use useQuery:-</h3><p><strong>Local UI state:-</strong> Things that <em>only affect local render</em>, not backend data:-</p><ul><li>Modal open/close</li><li>Form input values</li><li>Current tab index</li></ul><blockquote><em>Use </em><em>useState or </em><em>useReducer instead.</em></blockquote><p><strong>When doing POST/PUT/DELETE:-</strong></p><p>Those actions modify data — so you should use useMutation, not useQuery.</p><p><strong>One-time or static fetch with no reuse:-</strong></p><p>If fetching once and throwing away the result — useEffect may suffice.</p><pre>| Feature                | `useQuery`  | `useEffect` + `useState` |<br>| ---------------------- | ----------- | ------------------------ |<br>| Caching                | ✅           | ❌                        |<br>| Background refetch     | ✅           | ❌                        |<br>| Loading &amp; error states | Built-in    | Manual                   |<br>| Request deduplication  | ✅           | ❌                        |<br>| Clean API              | Declarative | More imperative          |<br>| Ideal for server state | Yes         | No                       |</pre><blockquote><em>The only thing </em><em>useEffect is better at is local UI logic, not server fetching.</em></blockquote><h3>Code Example:-</h3><pre>import { useQuery } from &#39;@tanstack/react-query&#39;;</pre><pre>const fetchTodos = () =&gt;<br>  fetch(&#39;https://example.com/webservice&#39;)<br>    .then(res =&gt; res.json());</pre><pre>function Todos() {<br>  const { data, isLoading, error } = useQuery({<br>    queryKey: [&#39;todos&#39;],<br>    queryFn: fetchTodos<br>  });</pre><pre>  if (isLoading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error loading todos&lt;/p&gt;;</pre><pre>  return (<br>    &lt;ul&gt;<br>      {data.map(todo =&gt; (<br>        &lt;li key={todo.id}&gt;{todo.title}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><h3>How many times does useQuery cause a component to render?</h3><p>useQuery can trigger multiple renders, but this is expected, controlled, and optimized.</p><h3>Typical Render Cycle of useQuery</h3><p>When a component uses useQuery, it usually renders 3–4 times in normal conditions.</p><p><strong>Initial render (mount)</strong></p><ul><li>Component mounts</li><li>Query starts fetching</li></ul><pre>State:isLoading: true<br>data: undefined<br>=============<br>First render</pre><p><strong>Fetching state update</strong></p><ul><li>React Query sets internal fetching state</li><li>isFetching: true</li></ul><pre>Second render (sometimes skipped due to batching)</pre><p><strong>Data received successfully</strong></p><ul><li>API call resolves</li><li>Data is stored in cache</li></ul><pre>State:isLoading: false<br>data: fetchedData<br><br>============<br>Third render</pre><p><strong>Background refetch (optional)</strong></p><p>Occurs when:</p><ul><li>Window refocus</li><li>Network reconnect</li><li>Stale time expires</li><li>Manual refetch()</li></ul><pre>isFetching: true (but data is still shown)<br><br>=============<br>Fourth render (if refetch happens)</pre><h3>Minimum &amp; Maximum Renders:-</h3><pre>| Scenario                         | Renders            |<br>| -------------------------------- | ------------------ |<br>| Fast API + cached data           | **1 render**       |<br>| Normal API call                  | **2–3 renders**    |<br>| With background refetch          | **3–4 renders**    |<br>| With polling (`refetchInterval`) | Multiple over time |</pre><h3>Example Timeline:-</h3><pre>Render #1 → loading<br>Render #2 → data loaded<br>Render #3 → background refetch (optional)</pre><h3>Important Optimization Features:-</h3><p><strong>Cached Data</strong></p><p>If data exists in cache and is not stale:</p><ul><li>Component renders once</li><li>No network call</li></ul><pre>useQuery({<br>  queryKey: [&#39;users&#39;],<br>  queryFn: fetchUsers,<br>  staleTime: 5 * 60 * 1000,<br>});</pre><p><strong>Structural Sharing</strong></p><p>Only re-renders if data actually changes.</p><p>Select Option (reduces re-renders)</p><pre>useQuery({<br>  queryKey: [&#39;users&#39;],<br>  queryFn: fetchUsers,<br>  select: data =&gt; data.users,<br>});</pre><p>Component re-renders only when users changes.</p><h3>Comparison with useEffect</h3><pre>| Aspect             | useQuery  | useEffect |<br>| ------------------ | --------- | --------- |<br>| Initial render     | 1         | 1         |<br>| After fetch        | 1         | 1         |<br>| Cache reuse        | Yes       | No        |<br>| Background refetch | Yes       | No        |<br>| Re-render control  | Optimized | Manual    |</pre><p>useEffect often causes more unnecessary renders due to manual state handling.</p><h3>Final Takeaways:-</h3><ol><li>Use useQuery for server-data fetching</li><li>Use useEffect for local state or side effects not related to data fetching</li><li>useQuery reduces boilerplate and improves performance with caching and auto-refetch.</li><li>useQuery re-renders only when query state changes (loading, error, or data). It does not re-render on every fetch unless the data or status actually changes.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eecd7dd54986" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving UI Responsiveness with React’s useTransition Hook]]></title>
            <link>https://medium.com/@manappa.kammar777/improving-ui-responsiveness-with-reacts-usetransition-hook-fdc889b9288f?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdc889b9288f</guid>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 10:38:38 GMT</pubDate>
            <atom:updated>2026-01-11T11:12:00.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9aam8Ylf-9RGlYs32Wr-w.png" /></figure><p>useTransition is a React 18+ hook that lets you mark some state updates as “non-urgent” or “low-priority,” so React can keep the UI responsive by rendering urgent updates first and delaying less critical updates.</p><p>useTransition allows React to <strong>pause non-essential updates</strong> and prioritize user interactions, keeping the app smooth and responsive even during heavy UI updates.</p><p>useTransition does NOT create a background thread. It tells React that some updates are low-priority, so React can delay, pause, or interrupt them to keep the UI responsive.</p><p><strong>Key Concepts Behind It:-</strong></p><ol><li><strong>Urgent vs Non-Urgent Updates:- </strong>In React, by default, all state updates are <strong>urgent</strong>. That means:</li></ol><ul><li>Every state change immediately triggers rendering.</li><li>If the UI update is heavy (like filtering 10,000 items), the app may <strong>lag</strong>, blocking user interactions like typing.</li></ul><p>useTransition solves this problem by letting you tell React:</p><ul><li>“This update is <strong>non-urgent</strong>. You can wait, pause, or even cancel it if the user interacts again.”</li></ul><p>2. <strong>Concurrent Rendering:-</strong></p><p>useTransition works because <strong>React 18 introduced Concurrent Mode</strong>:</p><ul><li>React can <strong>pause, resume, or restart rendering</strong>.</li><li>This allows <strong>user interactions</strong> (typing, clicks) to always remain <strong>smooth</strong>, even while React is working on heavy updates.</li></ul><h4><strong>Step-by-Step Flow</strong></h4><ol><li>User types in an input → urgent update (input value) → UI updates immediately.</li><li>Start a non-urgent update for filtering → React schedules it in the <strong>low-priority queue.</strong></li><li>If the user types again → React interrupts the previous low-priority update and <strong>starts the new one.</strong></li><li>Once low-priority work is done → updates the UI.</li><li>isPending is true during this process → can show “Loading…” feedback.</li></ol><h4>Why Use useTransition?</h4><ul><li>Makes <strong>UI feel fast and responsive.</strong></li><li>Handles <strong>expensive calculations or rendering</strong> without blocking the main thread.</li><li>Works perfectly with <strong>search, filtering, tab navigation, and pagination.</strong></li></ul><pre>User types →<br>Urgent update rendered immediately →<br>React schedules non-urgent update →<br>If user interacts again →<br>  React pauses the non-urgent work →<br>  Handles urgent update →<br>  Resumes non-urgent work later</pre><pre>import React, { useState, useTransition } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br><br>// Sample data (10,000 items to simulate heavy filtering)<br>const items = Array.from({ length: 10000 }, (_, i) =&gt; `Item ${i + 1}`);<br><br>function SearchList({ items }) {<br>  const [query, setQuery] = useState(&quot;&quot;);<br>  const [filteredQuery, setFilteredQuery] = useState(&quot;&quot;);<br><br>  const [isPending, startTransition] = useTransition();<br><br>  function handleChange(e) {<br>    const value = e.target.value;<br><br>    // 🔥 Urgent update (input should be instant)<br>    setQuery(value);<br><br>    // 🐢 Non-urgent update (heavy filtering)<br>    startTransition(() =&gt; {<br>      setFilteredQuery(value);<br>    });<br>  }<br><br>  // Filter items based on filteredQuery<br>  const filteredItems = items.filter((item) =&gt;<br>    item.toLowerCase().includes(filteredQuery.toLowerCase())<br>  );<br><br>  return (<br>    &lt;div style={{ padding: &quot;20px&quot; }}&gt;<br>      &lt;h2&gt;Search List (10,000 items)&lt;/h2&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={query}<br>        onChange={handleChange}<br>        placeholder=&quot;Type to search...&quot;<br>        style={{ padding: &quot;8px&quot;, width: &quot;300px&quot; }}<br>      /&gt;<br><br>      {isPending &amp;&amp; &lt;p style={{ color: &quot;orange&quot; }}&gt;Loading results...&lt;/p&gt;}<br><br>      &lt;ul style={{ maxHeight: &quot;400px&quot;, overflowY: &quot;scroll&quot; }}&gt;<br>        {filteredItems.slice(0, 50).map((item) =&gt; (<br>          &lt;li key={item}&gt;{item}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;p&gt;Showing first 50 results out of {filteredItems.length}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdc889b9288f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering React Hooks: Simplified Guide with Real-World Examples]]></title>
            <link>https://medium.com/@manappa.kammar777/mastering-react-hooks-simplified-guide-with-real-world-examples-486227532fc8?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/486227532fc8</guid>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 16:24:22 GMT</pubDate>
            <atom:updated>2025-06-14T16:27:04.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GahmCZwjDCcPQD6ttUpbA.png" /></figure><p>Learn the purpose and practical usage of key React Hooks — useCallback, useContext, useRef, useMemo, and useReducer — in a beginner-friendly way. This guide includes real-world examples and clear explanations to help you understand how to improve performance, manage complex state, avoid unnecessary re-renders, and access shared data across components. Whether you’re new to React or looking to solidify your hook knowledge, this breakdown simplifies advanced concepts for everyday use.</p><h3>useCallback:-</h3><p>In React, the useCallback hook is used to memoize a function so that it is not recreated on every render. This helps with performance optimization, especially when you pass callbacks to child components or use them in dependencies of other hooks like useEffect.</p><h4>Why use useCallback?</h4><ul><li>Prevent unnecessary re-renders: If a child component receives a callback as a prop, and that callback is re-created every render, the child may re-render unnecessarily. useCallback avoids this by returning the same function reference unless dependencies change.</li><li>Stable references for dependencies: If you’re using a function inside useEffect, useMemo, or other hooks that depend on references, using useCallback helps avoid unwanted re-executions.</li></ul><pre>// Parent component <br>import { useCallback, useState } from &#39;react&#39;<br>import ChildComponent from &#39;./childComponent&#39;;<br><br>export default function UseCallBackComponent() {<br>const [name, setName] = useState(&#39;John Doe&#39;);<br>const [name2, setName2] = useState(&#39;Sam joe&#39;);<br><br>const helloName = useCallback(() =&gt; {<br> console.log(&quot;Hello &quot; + name2);<br>}, [name2]);<br><br>return (<br>&lt;&gt;<br> &lt;ChildComponent helloName={helloName}/&gt;<br> &lt;input type=&quot;text&quot; value={name} onChange={(e) =&gt;  setName(e.target.value)} /&gt;<br> &lt;input type=&quot;text&quot; value={name2} onChange={(e) =&gt; setName2(e.target.value)} /&gt;<br> &lt;h2 onClick={()=&gt;setName(&quot;ABC&quot;)}&gt;UseCallBackComponent name Component&lt;/h2&gt;<br> &lt;h2 onClick={()=&gt;setName2(&quot;XYZ&quot;)}&gt;UseCallBackComponent name2  Component&lt;/h2&gt;<br> &lt;/&gt;<br>  );<br>}</pre><pre>// Child component<br>import { memo } from &quot;react&quot;;<br><br>function ChildComponent({helloName}) {<br>console.log(&quot;ChildComponent Rendered&quot;);  <br>  return helloName();<br>}<br><br>export default memo(ChildComponent);</pre><h4>without the useCallback:-</h4><ul><li>Every time UseCallBackComponent re-renders, it helloName is a new function, so it ChildComponent may unnecessarily re-render.</li></ul><h4>with useCallback:-</h4><ul><li>helloName is memoized and will only be recreated if its dependencies change. In the above example, name2 state changed than the renders that function.</li></ul><h3>useContext:-</h3><p>In React, createContext and useContext are used for managing and accessing global state or shared data across components without prop drilling.</p><h4>createContext — Creating a Context:-</h4><p>This function creates a Context object, which acts like a container for the shared value.</p><pre>// index component <br>import React, { createContext } from &quot;react&quot;<br>import ComponentOne from &quot;./useContextComponent/componentOne&quot;<br><br>const itemsContenxt = createContext()<br>const items = { food: &quot;Pizza&quot;, drink: &quot;Coke&quot; }<br><br>export default function About() {<br>  return (<br>      &lt;itemsContenxt.Provider value={items}&gt;<br>        &lt;ComponentOne /&gt;<br>      &lt;/itemsContenxt.Provider&gt;<br>  )<br>}<br><br>export { itemsContenxt }</pre><pre>import { useContext } from &quot;react&quot;<br>import { itemsContenxt } from &quot;../index&quot;;<br><br>export default function ComponentOne() {<br>const items = useContext(itemsContenxt);<br>return (<br> &lt;div&gt;<br>  &lt;p&gt;Food: {items.food}&lt;/p&gt;<br>  &lt;p&gt;Drink: {items.drink}&lt;/p&gt;<br> &lt;/div&gt;<br>  );<br>}</pre><h4>When to Use:-</h4><p>Use createContext and useContext when:</p><ul><li>You need to share theme, authentication status, user data, language, or settings across deeply nested components.</li><li>You want to avoid prop drilling (passing props through many layers).</li></ul><h3>useRef:-</h3><p>The useRef hook in React is used for accessing and persisting values across renders without triggering a re-render.</p><ul><li>Access DOM Elements:- You can directly interact with DOM elements (e.g., focus an input).</li><li>Store Mutable Values Without Causing Re-Renders:- If you want to keep a value between renders but not cause re-renders when it changes, use useRef.</li></ul><pre>import { useRef } from &quot;react&quot;;<br><br>function RefComponent() {<br> const inputRef = useRef(null);<br><br>// This function will be called when the button is clicked but it will not cause a re-render to show the updated value in the UI.<br><br> const showValue = () =&gt; {<br>    alert(`Input value: ${inputRef.current.value}`);<br> };<br><br>return (<br> &lt;&gt;<br>  &lt;h1&gt;ref value:- {inputRef.current &amp;&amp; inputRef.current.value}&lt;/h1&gt;<br>  &lt;input ref={inputRef} type=&quot;text&quot; placeholder=&quot;Enter your name&quot; /&gt;<br>  &lt;button onClick={showValue}&gt;Show Value&lt;/button&gt;<br> &lt;/&gt;<br>);<br>}<br><br>export default RefComponent;</pre><h3>useMemo:-</h3><p>The useMemo hook in React is not a component — it’s a React Hook used to optimize performance by memoizing the result of an expensive calculation or function, so that it’s only recalculated when its dependencies change.</p><ul><li>To avoid recalculating a value every time the component re-renders if the inputs (dependencies) haven’t changed.</li></ul><h4>When to use:-</h4><ul><li>Expensive calculations.</li><li>Avoiding the re-creation of objects or arrays that cause unnecessary re-renders.</li><li>Memoizing derived values inside functional components.</li></ul><pre>import React, { useMemo, useState } from &#39;react&#39;;<br><br>export default function MemoComponent() {<br>const [count, setCount] = useState(0);<br>const [doubleCount, setDoubleCount] = useState(0);<br>const [tripleCount, setTripleCount] = useState(0);<br><br>// Using useMemo to optimize the performance of a slow function<br>// that depends on doubleCount<br><br>// without useMemo, the slowFunction would run on every render of the state change<br>// with useMemo, it only runs when doubleCount changes<br><br>const getDouble = useMemo(()=&gt;slowFunction(doubleCount), [doubleCount]);<br><br>  return (<br>&lt;&gt;<br> &lt;h1&gt;MemoComponent&lt;/h1&gt;<br> &lt;h2&gt;Count: {count}&lt;/h2&gt;<br> &lt;button onClick={() =&gt; setCount(count+1)}&gt;setCount&lt;/button&gt;<br> &lt;h2&gt;Double Count: {doubleCount}&lt;/h2&gt;<br> &lt;button onClick={() =&gt; setDoubleCount(getDouble)}&gt;doubleCount&lt;/button&gt;<br> &lt;h2&gt;Triple Count: {tripleCount}&lt;/h2&gt;<br> &lt;button onClick={() =&gt; setTripleCount(tripleCount+3)}&gt;tripleCount&lt;/button&gt;<br>&lt;/&gt;<br>  );<br>}<br><br>function slowFunction(num) {<br>  for (let i = 0; i &lt; 1000000000; i++) {} // Simulating a slow operation<br>  return num * 2;<br>}</pre><h3>useReducer:-</h3><p>The useReducer hook (not a component) in React is used for managing complex state logic in a component. It’s an alternative to useState, and is especially useful when:</p><ul><li>You have multiple related state values.</li><li>You need complex state transitions (e.g. depending on the previous state).</li><li>You want a more predictable and testable state update logic, similar to Redux-style reducers.</li></ul><h4>Keywords in useReducer:-</h4><ul><li>reducer is a function that takes the current state and an action, and returns the new state.</li><li>initialState is the starting state.</li><li>dispatch is a function you use to send actions to update the state.</li></ul><pre>import { useReducer } from &quot;react&quot;;<br><br>const initialState = { count: 0, error: null };<br><br>function reducer(state, action) {<br>switch (action.type) {<br> case &#39;increment&#39;:<br> const newState = state.count + 1;<br> const hasError = newState &gt; 5; <br>  return { ...state, count: hasError ? state.count : newState, error: hasError ? &#39;Count cannot exceed 5&#39; : null };<br> case &#39;decrement&#39;:<br> const newCount = state.count - 1;<br> const hasDecrementError = newCount &lt; 0;<br>  return { ...state, count: hasDecrementError ? state.count : newCount, error: hasDecrementError ? &#39;Count cannot be negative&#39; : null };<br> case &#39;reset&#39;:<br>  return initialState;<br> case &#39;error&#39;:<br>  return { ...state, error: action.payload };<br> default:<br>  throw new Error(`Unknown action type: ${action.type}`);<br>  }<br>}<br><br>export default function ReducerComponent() {<br>const [state, dispatch] = useReducer(reducer, {count: 0, error: null});<br><br>return (<br>&lt;&gt;<br> &lt;h1&gt;Reducer Component&lt;/h1&gt;<br> &lt;p&gt;Count: {state.count}&lt;/p&gt;<br> {state.error &amp;&amp; &lt;p style={{ color: &#39;red&#39; }}&gt;{state.error}&lt;/p&gt;}<br> &lt;button onClick={() =&gt; dispatch({ type: &#39;increment&#39;   })}&gt;Increment&lt;/button&gt;<br> &lt;button onClick={() =&gt; dispatch({ type: &#39;decrement&#39; })}&gt;Decrement&lt;/button&gt;<br> &lt;button onClick={() =&gt; dispatch({ type: &#39;reset&#39; })}&gt;Reset&lt;/button&gt;<br> &lt;button onClick={() =&gt; dispatch({ type: &#39;error&#39;, payload: &#39;An error occurred!&#39; })}&gt;Trigger Error&lt;/button&gt;<br> &lt;p&gt;Reducer Component is used to manage complex state logic.&lt;/p&gt;<br>&lt;/&gt;<br>);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=486227532fc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Next.js and Its Routing Mechanism.]]></title>
            <link>https://medium.com/@manappa.kammar777/deep-dive-into-next-js-and-its-routing-mechanism-b03bb1170ecf?source=rss-87889aec0439------2</link>
            <guid isPermaLink="false">https://medium.com/p/b03bb1170ecf</guid>
            <dc:creator><![CDATA[Manappa Kammar]]></dc:creator>
            <pubDate>Sat, 31 May 2025 17:33:19 GMT</pubDate>
            <atom:updated>2025-06-01T11:20:26.590Z</atom:updated>
            <content:encoded><![CDATA[<p>A detailed understanding of Next.js and its routing mechanism involves knowing the behind-the-scenes process of how routing works. In Next.js, when files are created inside the pages folder, the framework automatically sets up routes based on the file structure. This allows Next.js to map URLs to the corresponding components without manual configuration.</p><h3>What is Next.js?</h3><p><strong>Next.js</strong> is a popular open-source React framework developed by Vercel. It enables developers to build fast, scalable, and production-ready web applications with features like server-side rendering, static site generation, API routes, and more — all with minimal configuration.</p><h3>Key Features of Next.js</h3><ol><li><strong>File-based Routing:- </strong>Pages are created by adding files to the pages/ (or app/) directory. Each file automatically becomes a route.</li><li><strong>Server-Side Rendering (SSR):- </strong>Pages can be rendered on the server at request time using getServerSideProps, providing up-to-date content and better SEO.</li><li><strong>Static Site Generation (SSG):- </strong>Pages can be pre-rendered at build time using getStaticProps, resulting in fast, cacheable static pages.</li><li><strong>Incremental Static Regeneration (ISR):- </strong>Update static content after deployment without rebuilding the whole site.</li><li><strong>Image Optimization:- </strong>Built-in &lt;Image /&gt; component for automatic image resizing, lazy loading, and optimization.</li><li><strong>Built-in CSS and Sass Support:- </strong>Import CSS and Sass files directly into your components.</li><li><strong>TypeScript Support:- </strong>First-class TypeScript integration for type-safe development.</li><li><strong>Fast Refresh &amp; Hot Reloading:- </strong>Instant feedback during development.</li><li><strong>Middleware &amp; Edge Functions:- </strong>Run code at the edge for authentication, redirects, and more.</li><li><strong>App Router (New):- </strong>The app/ directory introduces layouts, server components, and more flexible routing.</li></ol><h3>Advantages of Next.js</h3><ol><li><strong>SEO Friendly:- </strong>SSR and SSG provide better SEO compared to client-side-only React apps.</li><li><strong>Performance:- </strong>Automatic code splitting, static generation, and image optimization make apps fast.</li><li><strong>Developer Experience:- </strong>Simple setup, hot reloading, and built-in features reduce boilerplate and speed up development.</li><li><strong>Scalability:- </strong>Suitable for small sites, large apps, and everything in between.</li><li><strong>Fullstack Capabilities:- </strong>API routes and middleware allow you to build both frontend and backend in one project.</li><li><strong>Community &amp; Ecosystem:- </strong>Large community, extensive documentation, and many plugins/integrations.</li></ol><h3>Why Should You Use Next.js?</h3><ul><li>You want <strong>better SEO</strong> and performance than a typical React SPA.</li><li>You need a mix of <strong>static and dynamic pages</strong>.</li><li>You want to build <strong>fullstack applications</strong> with both frontend and backend logic.</li><li>You value <strong>developer productivity</strong> and a modern toolchain.</li></ul><h3>When to Use Next.js?</h3><ul><li><strong>Content-heavy websites:</strong> Blogs, marketing sites, documentation (for SSG/ISR).</li><li><strong>E-commerce:</strong> Product pages with SEO and dynamic data.</li><li><strong>Dashboards &amp; SaaS:</strong> Apps needing SSR, authentication, and API routes.</li><li><strong>Hybrid apps:</strong> Sites needing both static and dynamic content.</li></ul><h3>Data fetching methods in Next.js</h3><p>Below are the Data Fetching Methods (or life cycle methods ) in Next.js. They are used in <strong>page components</strong> to control <strong>how and when data is fetched</strong>.</p><p><strong>Server-Side Rendering (SSR)</strong></p><p><strong>Static Site Generation(SSG)</strong></p><p><strong>Client-Side Rendering(CSR)</strong></p><ol><li><strong>getStaticProps — </strong>“<strong><em>Build Time</em></strong>”<strong>:- </strong>Next.js runs this function once during the build process (when you run next build). The page is generated as a static HTML file with the data fetched at build time. Every user gets the same pre-rendered page until you rebuild and redeploy your app. This approach is ideal for content that doesn&#39;t change often (e.g., marketing pages, documentation). If the database is updated after the build, users will not see the new data until the app is rebuilt and redeployed.<br> This method runs at build time and follows the <strong>Static Site Generation (SSG)</strong> strategy. The function is called once during the build, and the returned props are used to generate a static HTML file.</li><li><strong>getServerSideProps — “<em>On Every Request</em></strong>”:- Next.js runs this function every time a user requests the page. The page is generated on the server with the latest data for each request, ensuring users always see the most up-to-date information. This approach is ideal for pages that require fresh data on every visit (e.g., dashboards, user profiles).<br> If you update your database, the next user to visit the page will immediately see the new data.<br> This method runs on every request and follows the <strong>Server-Side Rendering (SSR)</strong> strategy. The function is called on the server before the page is rendered, and the returned props are passed to your page component.</li><li><strong>getInitialProps</strong>:- This function runs on the server during the initial page load (SSR) and on the client during client-side navigation. It is a <strong>legacy method</strong> and is <strong>not recommended for new applications</strong>, as it disables some of Next.js’s automatic static optimizations.<br> <strong>Use case:</strong> When you need to fetch data both during the initial server load and on client-side navigation. However, it is generally better to use getServerSideProps or getStaticProps in modern apps.<br> If you use getInitialProps, it will run on both the server and the client, as described above.</li></ol><p>You <strong>cannot use all three data fetching methods (</strong>getServerSideProps<strong>, </strong>getStaticProps<strong>, and </strong>getInitialProps<strong>) in the same file</strong> because:</p><p><strong>1. Conflicting Data Fetching Strategies</strong></p><ul><li>getServerSideProps: Runs on every request (SSR).</li><li>getStaticProps: Runs at build time (SSG).</li><li>getInitialProps: Runs on both server and client (legacy, less efficient).</li></ul><p>Next.js will <strong>only use one</strong> data fetching method per page, based on priority:</p><ul><li>If getServerSideProps is present, it takes precedence (SSR).</li><li>If only getStaticProps is present, it uses SSG.</li><li>If only getInitialProps is present, it uses that (legacy).</li></ul><p><strong>2. Build Errors and Unexpected Behavior</strong></p><ul><li>If you define more than one of these in a single page, Next.js will throw a build error or ignore the others.</li><li>You must choose <strong>one</strong> data fetching method per page.</li></ul><p><strong><em>Note:- In summary, you must pick only one data fetching method per page file in the </em></strong><strong><em>pages/ directory. Defining more than one will cause errors or unexpected results.</em></strong></p><h3><strong>Commands to install the Next.js App:-</strong></h3><p>Below are the commands to create and run the app.</p><blockquote><em>npx create-next-app@latest</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSvNYPOmgSf9ztzENWSZhA.png" /><figcaption>steps to install the app</figcaption></figure><blockquote><em>npm run dev</em></blockquote><h3>What is happening in the routing part in Next.js</h3><p>How is Next.js able to track and render components when the browser navigates to a specific URL? In traditional frameworks, we explicitly define routes in a routing file, but in Next.js, simply creating a file in the pages or appdirectory automatically maps it to a route. Similarly, creating a folder creates a nested route. So, how does Next.js capture these routes and render the correct components behind the scenes?</p><p>So let us deep dive more into understanding the behind-the-story.</p><p>Next.js uses a <strong>file-based routing system</strong>. During the build process, it scans the pages/ directory and automatically generates a routing map based on the file and folder structure. When a user navigates to a URL, Next.js matches the path to the corresponding file in pages/ and renders that component. Dynamic routes are also supported using square brackets (e.g., [id].js).</p><p><strong>folder structure:-</strong></p><pre>pages<br>  about<br>    [id].js   =&gt;/about/:id<br>  about.js    =&gt;/about<br>  home.js     =&gt;/home<br>  index.js    =&gt;/</pre><p>The above defines the folder structure inside the Next.js app. When you run the app, it automatically creates routes in JSON format, which are later used by the Next.js server to determine which component to display for a given URL. This process generates a manifest.json file that maps each route to its corresponding component file.</p><pre>pages-manifest.json<br><br>{<br>  &quot;/_app&quot;: &quot;pages/_app.js&quot;,<br>  &quot;/_error&quot;: &quot;pages/_error.js&quot;,<br>  &quot;/_document&quot;: &quot;pages/_document.js&quot;,<br>  &quot;/&quot;: &quot;pages/index.js&quot;,<br>  &quot;/home&quot;: &quot;pages/home.js&quot;,<br>  &quot;/about/[id]&quot;: &quot;pages/about/[id].js&quot;,<br>  &quot;/about&quot;: &quot;pages/about.js&quot;<br>}<br><br><br>build-manifest.json<br><br>{<br>  &quot;polyfillFiles&quot;: [<br>    &quot;static/chunks/polyfills.js&quot;<br>  ],<br>  &quot;devFiles&quot;: [<br>    &quot;static/chunks/react-refresh.js&quot;<br>  ],<br>  &quot;ampDevFiles&quot;: [],<br>  &quot;lowPriorityFiles&quot;: [<br>    &quot;static/development/_buildManifest.js&quot;,<br>    &quot;static/development/_ssgManifest.js&quot;<br>  ],<br>  &quot;rootMainFiles&quot;: [],<br>  &quot;rootMainFilesTree&quot;: {},<br>  &quot;pages&quot;: {<br>    &quot;/&quot;: [<br>      &quot;static/chunks/webpack.js&quot;,<br>      &quot;static/chunks/main.js&quot;,<br>      &quot;static/chunks/pages/index.js&quot;<br>    ],<br>    &quot;/_app&quot;: [<br>      &quot;static/chunks/webpack.js&quot;,<br>      &quot;static/chunks/main.js&quot;,<br>      &quot;static/chunks/pages/_app.js&quot;<br>    ],<br>    &quot;/_error&quot;: [<br>      &quot;static/chunks/webpack.js&quot;,<br>      &quot;static/chunks/main.js&quot;,<br>      &quot;static/chunks/pages/_error.js&quot;<br>    ],<br>    &quot;/about&quot;: [<br>      &quot;static/chunks/webpack.js&quot;,<br>      &quot;static/chunks/main.js&quot;,<br>      &quot;static/chunks/pages/about.js&quot;<br>    ],<br>    &quot;/about/[id]&quot;: [<br>      &quot;static/chunks/webpack.js&quot;,<br>      &quot;static/chunks/main.js&quot;,<br>      &quot;static/chunks/pages/about/[id].js&quot;<br>    ]<br>  },<br>  &quot;ampFirstPages&quot;: []<br>}</pre><h3><strong>pages-manifest.json:-</strong></h3><p>The pages-manifest.json is a build artifact that maps your app’s routes to their compiled server files, enabling Next.js to efficiently serve the correct page for each URL in production.</p><p>If you change your routes or add new pages, just run next build again, and this file will update automatically.</p><p>The pages-manifest.json file is an <strong>internal manifest file generated by Next.js</strong> during the build process (next build). Here’s a detailed explanation:</p><p><strong>What does this file define?</strong></p><ul><li>It <strong>maps each route in your application to its corresponding compiled JavaScript file</strong> in the .next/server/pages/ directory.</li><li>The keys are the URL routes (e.g., /, /about, /about/[id]).</li><li>The values are the relative paths to the compiled page files (e.g., pages/index.js, pages/about.js).</li></ul><p><strong>When is this file created?</strong></p><ul><li>This file is <strong>automatically generated</strong> by Next.js <strong>every time you run </strong><strong>next build</strong>.</li><li>It is part of the .next build output, which contains all the compiled and optimized files needed for your app to run in production.</li></ul><p><strong>What is its purpose?</strong></p><ul><li><strong>Routing:</strong><br>Next.js uses this manifest at runtime to know which compiled file to load for each incoming request.</li><li><strong>Performance:</strong><br>It allows Next.js to quickly resolve routes to their corresponding server-rendered files without scanning the filesystem.</li><li><strong>Dynamic Routes:</strong><br>Handles both static and dynamic routes (like /about/[id]).</li></ul><h3><strong>build-manifest.json:-</strong></h3><p>This file <strong>maps each route to the JS chunks it needs</strong>.It allows Next.js to efficiently serve only the necessary files for each page, improving performance.</p><p>The build-manifest.json file is <strong>generated by Next.js during the build process</strong>. Here’s what it does and defines:</p><p><strong>When is this file used?</strong></p><ul><li>It is created <strong>when you run </strong><strong>next build</strong>.</li><li>It is used <strong>internally by Next.js</strong> at runtime to know which JavaScript and other static files are needed for each page.</li><li>It helps Next.js optimize loading and code splitting for your app.</li></ul><p><strong>What does it define?</strong></p><ul><li><strong>polyfillFiles</strong>: Lists polyfills needed for browser compatibility.</li><li><strong>devFiles</strong>: Files used in development mode (like hot reloading).</li><li><strong>lowPriorityFiles</strong>: Files that can be loaded with lower priority.</li><li><strong>pages: <br>Key:</strong> Each route in your app (e.g., /, /about, /about/[id]). <br><strong>Value:</strong> An array of chunk files (JavaScript) that are required to render that page.</li><li><strong>ampFirstPages</strong>: AMP-specific pages (if any).</li></ul><p><strong>How They Work Together</strong></p><ul><li><strong>pages-manifest.json:</strong><br>Used on the <strong>server</strong> to route incoming requests to the correct server-rendered page file.</li><li><strong>build-manifest.json:</strong><br>Used on the <strong>client</strong> (and server during SSR) to know which JS and static files to load for each page.</li></ul><p><strong>In summary of both JSON files:</strong></p><ul><li>When a user visits a URL, Next.js uses pages-manifest.json to find the server file to render the page.</li><li>Then, it uses build-manifest.json to inject the correct JS chunks into the HTML so the browser can load and hydrate the page.</li><li>These two files are located inside the .next folder, which is automatically generated by Next.js. We cannot modify them directly, but we can visualize what happens when a component is created inside the pages directory. When the app navigates to that URL, the corresponding route is automatically added in both files.</li></ul><h3>App Router:-</h3><p>When the App Router is used in a Next.js project, it creates a app directory inside the Next.js repo. This folder contains the component files for each route. However, components inside the app directory are <strong>React Server Components </strong>by default, which means you cannot use getStaticProps, getServerSideProps, or getInitialProps with them</p><p>The <strong>major issue</strong> is that the <strong>App Router</strong> (app/ folder) in Next.js <strong>does not support</strong> special data fetching functions like getServerSideProps. These functions are only supported in the <strong>Pages Router</strong> (pages/ folder).</p><p><strong>Why?</strong></p><ul><li>The App Router uses a new data fetching model based on <strong>React Server Components</strong> and async components.</li><li>In the app/ folder, fetch data by making your component async and using await fetch(...) directly inside the component.</li><li>It does <strong>not</strong> look for or execute getServerSideProps, getStaticProps, or getInitialProps.</li><li>If you try to use getServerSideProps in the app/ folder, it will be ignored, and you may get an error.</li></ul><h3>Page Router:-</h3><p>The <strong>Pages Router</strong> is the original routing system in Next.js, based on the pages/ directory.<br>Each file in the pages/ folder automatically becomes a route in your application.</p><p><strong>Key Features:-</strong></p><p>Data Fetching Methods:</p><ul><li>getStaticProps: Static Site Generation (SSG) at build time.</li><li>getServerSideProps: Server-Side Rendering (SSR) on every request.</li><li>getStaticPaths: For dynamic SSG routes.</li><li>getInitialProps: Legacy, runs on both server and client.</li></ul><p>Dynamic Routing:</p><ul><li>Use [param].js for dynamic segments (e.g., [id].js for /about/12).</li></ul><p>API Routes:</p><ul><li>Create backend endpoints in pages/api/.</li></ul><p>Custom App and Document:</p><ul><li>_app.js: Customizes the root React component.</li><li>_document.js: Customizes the HTML document structure.</li></ul><p>Error Handling:</p><ul><li>_error.js: Custom error page.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b03bb1170ecf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>