<?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 Amandeep Singh on Medium]]></title>
        <description><![CDATA[Stories by Amandeep Singh on Medium]]></description>
        <link>https://medium.com/@aman-deepsingh?source=rss-f11327daa55a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zsnwrU0ViwqGxasKjzvuXQ.jpeg</url>
            <title>Stories by Amandeep Singh on Medium</title>
            <link>https://medium.com/@aman-deepsingh?source=rss-f11327daa55a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:42:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aman-deepsingh/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[requestAnimationFrame in JavaScript ?]]></title>
            <link>https://aman-deepsingh.medium.com/requestanimationframe-in-javascript-ce9e853dc064?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9e853dc064</guid>
            <category><![CDATA[css-animation]]></category>
            <category><![CDATA[setinterval]]></category>
            <category><![CDATA[requestanimationframe]]></category>
            <category><![CDATA[settimeout]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 07:24:05 GMT</pubDate>
            <atom:updated>2026-01-13T07:25:24.754Z</atom:updated>
            <content:encoded><![CDATA[<h3>requestAnimationFrame in JavaScript, the easy way.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLd1Xacj9S7blA8FCr2Aeg.jpeg" /></figure><p>There was a time when I thought animations in JavaScript were simple.</p><blockquote><em>“Just use </em><em>setInterval every 16ms. 60fps achieved. Done.” 😌</em></blockquote><p>Then came:</p><ul><li>jittery animations</li><li>battery drain on laptops</li><li>scroll lag</li><li>and Chrome DevTools screaming <strong>“Long task”</strong></li></ul><p>That’s when I met <strong>requestAnimationFrame</strong> — and realised browsers are way smarter than I gave them credit for.</p><h3>The Real Problem With JS Animations</h3><p>Let’s start with a truth bomb:</p><p>👉 <strong>JavaScript does not control the screen. The browser does.</strong></p><p>The browser:</p><ul><li>decides when to repaint</li><li>decides when to reflow</li><li>decides when to composite layers</li><li>decides how often frames are drawn</li></ul><p>But setTimeout and setInterval don’t care about any of this.</p><p>They just shout:</p><blockquote><em>“Run this callback after X milliseconds 😤”</em></blockquote><p>The browser then tries to <em>somehow</em> fit that request into its rendering pipeline.</p><p>That mismatch is where problems begin.</p><h3>What Is a “Frame” Anyway?</h3><p>Before requestAnimationFrame, you need to understand <strong>frames</strong>.</p><p>Most screens refresh at <strong>60Hz</strong><br> That means:</p><pre>60 frames per second<br>≈ one frame every 16.67ms</pre><p>Frame is like a single visual snapshot of UI. Think of it like a screenshot of running video :)</p><p>For every frame, the browser roughly does:</p><ol><li>Run JavaScript</li><li>Calculate styles</li><li>Layout (reflow)</li><li>Paint</li><li>Composite</li><li>Display frame</li></ol><p>If your JS runs <strong>out of sync</strong> with this cycle — welcome to jank city 🏙️</p><h3>Enter requestAnimationFrame</h3><p>requestAnimationFrame is the browser saying:</p><blockquote><em>“If you want to animate, tell me </em>what<em> you want to change — <br> I’ll decide </em>when<em> to do it.”</em></blockquote><p>Instead of forcing execution, you <strong>request</strong> it.</p><pre>requestAnimationFrame(callback);</pre><p>That callback:</p><ul><li>runs <strong>before the next repaint</strong></li><li>runs <strong>once per frame</strong></li><li>automatically pauses in inactive tabs</li><li>syncs perfectly with the browser’s render cycle</li></ul><h3>A Simple Mental Model</h3><h3>❌ setTimeout</h3><p>“Run this code after 16ms, I don’t care what else is happening.”</p><h3>✅ requestAnimationFrame</h3><p>“Hey browser, whenever you’re about to draw the next frame, run this.”</p><p>That difference is <em>huge</em>.</p><h3>Basic Example: Moving a Box</h3><pre>let x = 0;<br>function move() {<br>  x += 2;<br>  box.style.transform = `translateX(${x}px)`;<br>  requestAnimationFrame(move);<br>}<br><br>requestAnimationFrame(move);</pre><p>Why this feels smooth:</p><ul><li>updates happen <strong>right before repaint</strong></li><li>no unnecessary extra renders</li><li>browser optimizes the whole thing</li></ul><h3>Why Animations Feel Smoother with requestAnimationFrame</h3><h3>1️⃣ Frame-perfect timing</h3><p>Your code runs at the <strong>exact right moment</strong>, not “whenever JS feels like it”.</p><h3>2️⃣ Automatic throttling</h3><p>Switch tabs?<br>Animation pauses.<br>Battery saved 🔋</p><h3>3️⃣ No frame stacking</h3><p>setTimeout can queue callbacks even when the browser is busy.<br> requestAnimationFrame won’t.</p><h3>4️⃣ Works with the browser, not against it</h3><p>Layout, paint, and JS happen in harmony.</p><h3>“Why Not Just Use setInterval(16)?”</h3><p>This is an interview classic — and a real-world trap.</p><pre>setInterval(() =&gt; {<br>  animate();<br>}, 16);</pre><p>Looks fine. Isn’t.</p><p><strong>Problems:</strong></p><ul><li>16ms is a <em>guess</em>, not a guarantee</li><li>callbacks can pile up</li><li>animations keep running in background tabs</li><li>browser repaint may not align with execution</li></ul><p>Result: dropped frames + wasted CPU.</p><p>I hope I was able to explain this topic in way you guys understand :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9e853dc064" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering the Global Execution Context in JavaScript]]></title>
            <link>https://aman-deepsingh.medium.com/mastering-the-global-execution-context-in-javascript-719ad10f99e5?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/719ad10f99e5</guid>
            <category><![CDATA[global-execution-context]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 10:20:14 GMT</pubDate>
            <atom:updated>2025-09-01T10:20:14.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHmt6fu4lxs9y6nNC0T6ig.jpeg" /></figure><p><strong>“How does JavaScript know where to start?”</strong>, the answer lies in the <strong>Global Execution Context (GEC)</strong>.</p><p>This is the <strong><em>foundation stone</em></strong> of how JS code runs. ✨</p><p>I will be explaining everything I have learned about Execution Context so far :)</p><h3>🔹 What is an Execution Context?</h3><p>An <strong>Execution Context</strong> is like a box where JavaScript code runs.</p><p>Think of it as a room that contains everything JS needs to execute your code:</p><ul><li>🗂 <strong>Variable Environment</strong> (variables, functions, arguments)</li><li>🗺 <strong>Lexical Environment</strong> (scope + references to outer scope)</li><li>🪞 <strong>this binding</strong></li><li>🧵 <strong>Scope chain</strong></li></ul><p>And the very first room created is the <strong>Global Execution Context (GEC)</strong>.</p><h3>🔹 Types of Execution Contexts</h3><p>JavaScript creates different contexts depending on what’s running:</p><ol><li><strong>Global Execution Context (GEC)</strong></li></ol><ul><li>Created once when JS starts.</li><li>Linked to the <em>global object</em> (window in browser, global in Node.js).</li><li>Only one GEC can exist (important buddy).</li></ul><p>2. <strong>Function Execution Context (FEC)</strong></p><ul><li>Created every time a function is invoked.</li><li>Each call has its own little room.</li></ul><h3>🔹 How GEC is Created (The Two Phases)</h3><p>When your JS program runs, the <strong>GEC is created in two steps</strong>:</p><h3>1. Creation Phase (Memory Allocation)</h3><ul><li>JS scans your code first.</li><li>All variables declared with var are hoisted → initialized as undefined.</li><li>Functions are hoisted with their full definition.</li><li>let and const are also hoisted but remain in the <strong>Temporal Dead Zone (TDZ)</strong>.</li><li>Global object (window in browsers) is created.</li><li>this is set to global object.</li></ul><p>Example:</p><pre>console.log(x);   // undefined<br>console.log(foo); // [function: foo]<br>var x = 10;<br>function foo() {<br>  return &quot;Hello&quot;;<br>}</pre><p>During this phase:</p><ul><li>x = undefined</li><li>foo = function reference</li></ul><h3>2. Execution Phase</h3><ul><li>Now the code runs line by line.</li><li>Variables get assigned values.</li></ul><p>Continuing the example:</p><ul><li>x becomes 10.</li></ul><h3>🔹 The Call Stack and GEC</h3><p>JS is single-threaded and uses a <strong>call stack</strong> (LIFO).</p><p>Steps:</p><ol><li>Program starts → GEC created and pushed onto stack.</li><li>A function is called → new Function Execution Context is created and pushed.</li><li>When function finishes → popped off stack.</li><li>When the program ends → GEC is popped.</li></ol><p>Example:</p><pre>function one() {<br>  console.log(&quot;One&quot;);<br>  two();<br>}<br>function two() {<br>  console.log(&quot;Two&quot;);<br>}<br>one();</pre><p>🗂 Call Stack sequence:</p><ul><li>GEC created.</li><li>one() → FEC for one.</li><li>Inside one, two() → FEC for two.</li><li>two finishes → popped.</li><li>one finishes → popped.</li><li>Program ends → GEC popped.</li></ul><h3>🔹 this in the Global Execution Context</h3><ul><li>In <strong>browsers</strong>: this === window</li><li>In <strong>Node.js</strong>: this === {}</li></ul><pre>console.log(this); // window (browser)<br><br>&quot;use strict&quot;;<br><br>console.log(this); // undefined</pre><h3>🔹 Common Interview Traps</h3><h3>1. Hoisting with var vs let/const</h3><pre>console.log(a); // undefined<br>console.log(b); // ReferenceError<br>var a = 10;<br>let b = 20;</pre><p>👉 var is hoisted as undefined.<br> 👉 let &amp; const are hoisted too but stuck in TDZ.</p><h3>2. Global Scope Pollution</h3><pre>var x = 5; // attaches to window<br>let y = 10; // does NOT attach<br>console.log(window.x); // 5<br>console.log(window.y); // undefined</pre><h3>3. Strict Mode this</h3><pre>console.log(this); // window<br>&quot;use strict&quot;;<br>console.log(this); // undefined</pre><h3>🎯 Key Takeaways</h3><ul><li>GEC is the <strong>first context</strong> created when JS runs.</li><li>It has <strong>two phases</strong>: memory allocation (hoisting) + execution.</li><li>Sits at the <strong>bottom of the call stack</strong>.</li><li>this in GEC → global object (window in browsers)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=719ad10f99e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ What “Lightweight Copy” Really Means ? Virtual DOM in React:]]></title>
            <link>https://aman-deepsingh.medium.com/what-lightweight-copy-really-means-virtual-dom-in-react-d2ad73cb8676?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2ad73cb8676</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[virtual-dom]]></category>
            <category><![CDATA[react-interview]]></category>
            <category><![CDATA[objects-in-javascript]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 06:51:13 GMT</pubDate>
            <atom:updated>2025-08-14T06:51:13.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>💡 What “Lightweight Copy” Really Means ? Virtual DOM in React:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gz2N4wEvuSEv8jw0zTDS8A.jpeg" /><figcaption>@clickbyamandeep (instagram)</figcaption></figure><p>Recently, during a React interview, I asked a candidate:</p><blockquote><strong><em>“Can you explain the Virtual DOM in React?”</em></strong></blockquote><p>The candidate confidently replied:</p><blockquote>“It’s a <strong>lightweight copy</strong> of the real DOM. Doing operations on the real DOM is expensive, but on the virtual DOM it’s not.”</blockquote><p>I nodded, then followed up:</p><blockquote><strong><em>“What does ‘lightweight copy’ mean exactly — and why is it not expensive on the Virtual DOM?”</em></strong></blockquote><p>That’s when the candidate paused. The conversation stalled.<br> And honestly? I’ve seen this pattern often — most developers <em>know</em> the phrase, but few can explain what it really means.</p><p>Let’s break it down and clear up the confusion. 🚀</p><h3>🏗 The Real DOM</h3><p>The <strong>DOM</strong> (Document Object Model) is the browser’s <em>live</em> representation of your web page.<br> It’s a <strong>complex, tree-like structure</strong> with:</p><ul><li>Tons of properties and methods</li><li>References to styles, layout, and events</li><li>Live connections to rendering logic</li></ul><p>Updating the real DOM is <strong>resource-heavy</strong> because every change can trigger:</p><ul><li><strong>Layout recalculations</strong> 🧮</li><li><strong>Repaints</strong> 🎨</li><li><strong>Reflows</strong> 🌀</li></ul><p>That’s why <strong>frequent DOM updates can slow down performance</strong> in complex UIs.</p><h3>🪞 The Virtual DOM</h3><p>React’s <strong>Virtual DOM</strong> is <strong>not</strong> a full clone of the real DOM.<br> Instead, it’s a <strong>simplified JavaScript object tree</strong> that contains just the <em>essential</em> information about your UI:</p><ul><li><strong>Element types</strong> (div, span, input, etc.)</li><li><strong>Attributes/props</strong> (className, style, etc.)</li><li><strong>Children</strong> (nested elements)</li></ul><p>It leaves out:</p><ul><li>Browser-specific details</li><li>Event listeners</li></ul><p>This stripped-down structure is what people mean when they say <em>“lightweight copy”</em>.</p><h3>🔍 What “Lightweight Copy” Really Means</h3><h3>1️⃣ Minimalist Structure</h3><p>The Virtual DOM <strong>only</strong> stores data React needs for comparison. No extra baggage.</p><h3>2️⃣ Pure JavaScript Objects</h3><p>No heavy browser APIs — just simple, serializable objects. This makes them <strong>fast to create, modify, and traverse</strong>.</p><h3>3️⃣ No Immediate Rendering</h3><p>When you update state in React, changes are made <strong>only</strong> to the Virtual DOM first.<br> The real DOM stays untouched until React finishes figuring out what’s different.</p><h3>4️⃣ Performance-Oriented Diffing</h3><p>React compares (diffs) the <strong>old Virtual DOM</strong> with the <strong>new one</strong>, calculates the minimal set of changes, and <strong>updates only what’s necessary</strong> in the real DOM — often in batches.</p><h3>⚡ Why This Makes Updates Cheaper</h3><p>Updating a JavaScript object in memory is <strong>way faster</strong> than manipulating the real DOM in the browser.<br> This allows React to:</p><ul><li>Reduce unnecessary re-renders</li><li>Avoid expensive DOM operations</li><li>Keep your app feeling <strong>snappy</strong> even as it grows</li></ul><h3>🧠 The Key Takeaway</h3><p>When we say the Virtual DOM is a “lightweight copy,” we mean:</p><blockquote><em>It’s a </em><strong><em>simplified, minimal representation of the UI</em></strong><em> stored in memory, which React uses to figure out the most efficient way to update the real DOM.</em></blockquote><p>This is why making changes to the Virtual DOM is <strong>fast</strong>, and why React apps scale so well in terms of performance.</p><p>💬 <strong>Your turn</strong> — Have you ever been asked this question in an interview? How would <em>you</em> explain “lightweight copy”? Drop your version in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2ad73cb8676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Fat Arrows Gone Wrong: When NOT to Use Arrow Functions in JavaScript ?]]></title>
            <link>https://aman-deepsingh.medium.com/fat-arrows-gone-wrong-when-not-to-use-arrow-functions-in-javascript-31b0e9d1e816?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b0e9d1e816</guid>
            <category><![CDATA[fat-arrow]]></category>
            <category><![CDATA[functions-in-javascript]]></category>
            <category><![CDATA[arrow-functions]]></category>
            <category><![CDATA[this-in-javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 11:06:02 GMT</pubDate>
            <atom:updated>2025-08-05T11:06:02.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚫 Fat Arrows Gone Wrong: When NOT to Use Arrow Functions in JavaScript ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHmt6fu4lxs9y6nNC0T6ig.jpeg" /></figure><h3>🧠 Quick Refresher: What’s an Arrow Function?</h3><pre>const sayHello = (name) =&gt; {<br>  console.log(`Hi, ${name}!`);<br>};</pre><p>Simple, right? No function keyword, no return if it&#39;s one-liner, and they lexically bind this. Sounds awesome?</p><p><strong>Not always. Let’s dive into the gotchas 👇</strong></p><h3>1. ❌ When You Need Access to this (Object Methods)</h3><p>Arrow functions <strong>don’t have their own </strong><strong>this</strong>. They grab it from the outer scope.</p><h3>😵 The Oops Moment:</h3><pre>const user = {<br>  name: &#39;Amandeep&#39;,<br>  greet: () =&gt; {<br>    console.log(`Hi, I am ${this.name}`);<br>  }<br>};<br>user.greet(); // ❌ Hi, I am undefined</pre><h3>✅ The Fix:</h3><pre>const user = {<br>  name: &#39;Amandeep&#39;,<br>  greet() {<br>    console.log(`Hi, I am ${this.name}`);<br>  }<br>};<br>user.greet(); // ✅ Hi, I am Amandeep</pre><p>🧘‍♂️ Moral: If you want to use this inside an object method, don’t use arrow functions.</p><h3>2. ❌ When You Need the arguments Object</h3><p>Arrow functions don’t have their own arguments object. They’ll throw a tantrum if you ask for it. 😤</p><h3>😵 The Oops Moment:</h3><pre>const logArgs = () =&gt; {<br>  console.log(arguments);<br>};<br>logArgs(1, 2, 3); // ❌ ReferenceError: arguments is not defined</pre><h3>✅ The Fix:</h3><pre>function logArgs() {<br>  console.log(arguments); // ✅ [1, 2, 3]<br>}<br>logArgs(1, 2, 3);</pre><p>📦 Use regular functions if you need to handle a variable number of arguments.</p><h3>3. ❌ When You’re Creating a Constructor</h3><p>Arrow functions are <strong>not constructible</strong> — you can’t use new with them.</p><h3>😵 The Oops Moment:</h3><pre>const Person = (name) =&gt; {<br>  this.name = name;<br>};<br>const p = new Person(&#39;Aman&#39;); // ❌ TypeError: Person is not a constructor</pre><h3>✅ The Fix:</h3><pre>function Person(name) {<br>  this.name = name;<br>}<br>const p = new Person(&#39;Aman&#39;); // ✅ All good!</pre><p>🔧 Constructors need their own this, which arrow functions can’t provide.</p><h3>4. ❌ When You’re Handling DOM Events (And Need ‘this’)</h3><p>Arrow functions inherit this, so inside a DOM event, this won&#39;t be the element you expect.</p><h3>😵 The Oops Moment:</h3><pre>document.querySelector(&#39;button&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>  console.log(this); // ❌ not the button element<br>});</pre><h3>✅ The Fix:</h3><pre>document.querySelector(&#39;button&#39;).addEventListener(&#39;click&#39;, function () {<br>  console.log(this); // ✅ refers to the button element<br>});</pre><p>📍 Use function() when this matters in event handling.</p><h3>5. ❌ When Defining Prototype Methods in Classes</h3><p>Arrow functions won’t bind to the class instance correctly if used as methods.</p><pre>class Timer {<br>  constructor() {<br>    this.seconds = 0;<br>  }<br>start = () =&gt; { // Works here because it&#39;s a class field<br>    setInterval(() =&gt; {<br>      this.seconds++;<br>      console.log(this.seconds);<br>    }, 1000);<br>  };<br>}</pre><p>🧠 Just remember: for class prototype methods where this is critical — be cautious with arrows.</p><h3>✅ So, When SHOULD You Use Arrow Functions?</h3><ul><li>In short, clean one-liners 😍</li><li>Inside array methods (map, filter, reduce, etc.)</li><li>When you <strong>want to keep </strong><strong>this from outer scope</strong></li><li>In React callbacks (e.g., onClick={() =&gt; doSomething()})</li></ul><h3>🧪 TL;DR Cheat Sheet</h3><p>✅ Use Arrow ❌ Avoid Arrow Short functions Object methods needing this Callbacks in map, filter Constructor functions Lexical this is useful Using arguments React inline event handlers DOM event handlers needing this</p><h3>🎉 Final Thoughts</h3><p>Arrow functions are cool 😎 but not magical 🧙. They shine when used right and cause chaos when misused.</p><p>When in doubt — ask yourself:</p><blockquote><em>“Do I need my own </em><em>this or </em><em>arguments here?”</em></blockquote><p>If yes → go old-school with function.<br> If no → arrow away ➡️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b0e9d1e816" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Lifecycle Methods Bollywood Style mein ⚛]]></title>
            <link>https://aman-deepsingh.medium.com/react-lifecycle-methods-bollywood-style-mein-b97f6bf274ac?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b97f6bf274ac</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook-useeffect]]></category>
            <category><![CDATA[lifecycle-methods]]></category>
            <category><![CDATA[componentdidmount]]></category>
            <category><![CDATA[react-components]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 09:35:22 GMT</pubDate>
            <atom:updated>2025-07-30T09:35:22.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHmt6fu4lxs9y6nNC0T6ig.jpeg" /></figure><blockquote><em>“React components are like Bollywood heroes — they have a dramatic </em><strong><em>entry</em></strong><em>, an intense </em><strong><em>journey</em></strong><em>, and a tragic (or happy?) </em><strong><em>exit</em></strong><em>.” 🎬</em></blockquote><p>But what most devs don’t know is that <strong>React doesn’t just throw components on screen randomly</strong>. There’s a <em>systematic ritual</em>, like a shaadi function — <strong>with phases, order, and a lot of drama!</strong></p><p>So buckle up, kyunki aaj hum seekhne wale hain:</p><h3>🎭 The 3 Phases of a React Component</h3><ol><li><strong>Mounting</strong> — <em>Component takes birth and enters DOM</em> 👶</li><li><strong>Updating</strong> — <em>Component changes due to props/state updates</em> 🔁</li><li><strong>Unmounting</strong> — <em>Component gets removed from the DOM (RIP)</em> ⚰️</li></ol><p>Optional:</p><blockquote><strong><em>Error Phase</em></strong><em> — Jab kuch toot jaaye 😵 (Error boundaries handle this)</em></blockquote><p>Let’s break down each phase <strong>in order</strong>, with <strong>all lifecycle methods</strong>, <strong>funny examples</strong>, and <strong>modern functional equivalents</strong> with Hooks.</p><h3>🌱 1. MOUNTING PHASE — “Swagat nahi karoge hamara?” 🎉</h3><p>This is when the component is being created and inserted into the DOM for the first time.</p><h3>🧓 Class Component: Lifecycle Methods (in order)</h3><p>constructor() Initial setup (state, bindings).</p><p>static getDerivedStateFromProps() (Rarely used and please use this less this method is prone to errors 🚩) Sync state with props.</p><p>render() Returns the JSX 😃 we all know this.</p><p>componentDidMount() Component is on screen. Perfect for API calls.</p><h4>🎬 Example:</h4><pre>class Welcome extends React.Component {<br><br>  constructor(props) {<br>    super(props);<br>    this.state = { message: &#39;Namaste Duniya&#39; };<br>    console.log(&#39;👷 constructor&#39;);<br>  }<br><br>  static getDerivedStateFromProps(props, state) {<br>      console.log(&#39;📦 getDerivedStateFromProps&#39;);<br>      return null; // usually no changes<br>    }<br><br>    componentDidMount() {<br>      console.log(&#39;🎉 componentDidMount&#39;);<br>      // Fetch data, set up listeners<br>    }<br>    render() {<br>      console.log(&#39;🖼 render&#39;);<br>      return &lt;h1&gt;{this.state.message}&lt;/h1&gt;;<br>    }<br>  }</pre><h4>🪄 Functional Equivalent:</h4><pre>function Welcome() {<br>  const [message, setMessage] = useState(&#39;Namaste Duniya&#39;);<br><br>  useEffect(() =&gt; {<br>      console.log(&#39;🎉 componentDidMount equivalent&#39;);<br>      // Fetch data here<br>      return () =&gt; {<br>        console.log(&#39;💀 componentWillUnmount equivalent&#39;);<br>      };<br>    }, []); // empty deps = run only on mount<br>    return &lt;h1&gt;{message}&lt;/h1&gt;;<br>  }</pre><blockquote><em>“When </em><em>useEffect(..., []) runs — a new component is born!”</em></blockquote><h3>🔁 2. UPDATING PHASE — “Zindagi badal gayi, par component zinda hai!” 😆</h3><p>This phase is triggered <strong>every time props or state changes</strong>.</p><h3>🧓 Class Component: Lifecycle Methods (in order)</h3><p>All these will be called in synchronously :)</p><p>static getDerivedStateFromProps() Again gets called before every render (rarely used).</p><p>shouldComponentUpdate() Decide whether to re-render. If we return ‘false’ then render() method will not be executed.</p><p>render() UI re-renders.</p><p>getSnapshotBeforeUpdate() Capture info (like scroll position of user) before DOM updates.</p><p>componentDidUpdate() Do side effects after DOM update.</p><h4>🎬 Example:</h4><pre>class Counter extends React.Component {<br>  constructor() {<br>    super();<br>    this.state = { count: 0 };<br>  }<br><br>  static getDerivedStateFromProps() {<br>    console.log(&#39;📦 getDerivedStateFromProps (update)&#39;);<br>    return null;<br>  }<br><br>  shouldComponentUpdate() {<br>    console.log(&#39;❓ shouldComponentUpdate&#39;);<br>    return true;<br>  }<br><br>  getSnapshotBeforeUpdate(prevProps, prevState) {<br>    console.log(&#39;📸 getSnapshotBeforeUpdate&#39;);<br>    return null;<br>  }<br><br>  componentDidUpdate(prevProps, prevState, snapshot) {<br>    console.log(&#39;🔄 componentDidUpdate&#39;);<br>  }<br><br>  render() {<br>    console.log(&#39;🖼 render&#39;);<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;{this.state.count}&lt;/h1&gt;<br>        &lt;button onClick={() =&gt; this.setState({ count: this.state.count + 1 })}&gt;<br>          ➕<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><h3>🪄 Functional Equivalent:</h3><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&#39;🔄 componentDidUpdate equivalent for `count`&#39;);<br>  }, [count]); // runs when count changes<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{count}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;➕&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><blockquote><em>❗ </em><em>getSnapshotBeforeUpdate() and </em><em>shouldComponentUpdate() don’t have direct hook equivalents — but:</em></blockquote><ul><li>You can <strong>optimize re-renders</strong> using React.memo</li><li>Use useRef() to <strong>track snapshots</strong> manually</li></ul><p>I haven’t used <em>getSnapshotBeforeUpdate() till now in my react journey.</em></p><p>📸 <strong>MEME TIME :)</strong></p><blockquote>Shahrukh Khan shouting from a train<em><br> </em><em>&quot;Every time state changes — useEffect be like: &#39;Palat... palat... update ho gaya&#39; 🔁&quot;</em></blockquote><h3>💀 3. UNMOUNTING PHASE — “Alvida component…” 💔</h3><p>This is when the component is removed from DOM.</p><h3>🧓 Class Component</h3><p>Method Description componentWillUnmount() Clean up timers, subscriptions, listeners, etc.</p><pre>componentWillUnmount() {<br>  console.log(&#39;💣 Cleaning up before component dies&#39;);<br>}</pre><h3>🪄 Functional Equivalent</h3><pre>useEffect(() =&gt; {<br>  // setup code...<br>return () =&gt; {<br>    console.log(&#39;💣 useEffect cleanup on unmount&#39;);<br>  };<br>}, []);</pre><p>📸 <strong>MEME TIME :)</strong></p><blockquote><em>&quot;componentWillUnmount() called. The end.</em></blockquote><h3>⚠️ BONUS PHASE: ERROR HANDLING 😵</h3><p>When things break, React lets you <strong>catch errors gracefully</strong>.</p><h3>🧓 Class Component Only</h3><pre>componentDidCatch(error, info) {<br>  console.log(&#39;🚨 Caught error:&#39;, error);<br>}<br><br>static getDerivedStateFromError(error) {<br>  return { hasError: true };<br>}</pre><p>✅ <strong>Used in Error Boundaries</strong><br> ❌ No Hook alternative (yet).</p><h3>🎯 Final Thoughts</h3><blockquote><em>React Lifecycle = “Entry ➡️ Update ➡️ Exit”<br>Hooks make this cleaner, but not everything has a direct equivalent.<br>Don’t just memorize — </em>understand when &amp; why each method runs<em>. 😎</em></blockquote><h3>🤓 Your Homework</h3><ol><li>Replace all your old class components with functional ones.</li><li>Add a console.log() in useEffect and track the mount/update/unmount flow.</li><li>Share a React meme in the comments 💬</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b97f6bf274ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Promises in JavaScript — From Callback Hell to Promise Heaven ]]></title>
            <link>https://aman-deepsingh.medium.com/mastering-promises-in-javascript-from-callback-hell-to-promise-heaven-d9f628d1d625?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9f628d1d625</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[callback-hell]]></category>
            <category><![CDATA[callbacks-vs-promises]]></category>
            <category><![CDATA[callback-function]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 07:25:36 GMT</pubDate>
            <atom:updated>2025-07-30T07:25:36.212Z</atom:updated>
            <content:encoded><![CDATA[<h3>🤝 Mastering Promises in JavaScript — From Callback Hell to Promise Heaven 🚀</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*an-UstwyCE6obBCYk9FFDA.jpeg" /></figure><p>Let’s face it — the first time someone says “promise” in JavaScript, you expect it to be like a real-life promise.</p><p>But then JavaScript hits you with:</p><blockquote>“I promise… but you’ll have to<em> </em><em>.then() </em>and<em> </em><em>.catch() </em>me.” 🤯</blockquote><p>We’ll go from the basics of Promises to advanced tricks — with <strong>clear examples</strong>, <strong>funny memes</strong>, and <strong>zero callback hell</strong> 🧵👇</p><h3>🧠 What is a Promise?</h3><p>A <strong>Promise</strong> is an object representing the eventual completion (or failure) of an async operation.</p><p>In desi terms:</p><blockquote><em>Aapka kaam ho jaayega, bas thoda intezaar kijiye. :)</em></blockquote><h3>🧵 The Lifecycle of a Promise</h3><p>A Promise can be in one of 3 states:</p><p>State Description pending Initial state – still waiting <br>fulfilled Operation completed successfully 🎉 <br>rejected Operation failed 💥</p><h3>🏗️ Creating a Promise</h3><pre>const myPromise = new Promise((resolve, reject) =&gt; {<br>  const success = true;<br>   if (success) {<br>    resolve(&quot;✅ Promise fulfilled!&quot;);<br>  } else {<br>    reject(&quot;❌ Promise rejected!&quot;);<br>  }<br>});</pre><blockquote><strong>Note:</strong><em> </em><em>resolve </em>is for success,<em> </em><em>reject </em>is for failure.</blockquote><h3>⚡ Consuming a Promise</h3><pre>myPromise<br>  .then((result) =&gt; {<br>    console.log(result); // ✅ Promise fulfilled!<br>  })<br>  .catch((error) =&gt; {<br>    console.log(error); // ❌ Promise rejected!<br>  })<br>  .finally(() =&gt; {<br>    console.log(&quot;Cleanup logic here ✅&quot;);<br>  });</pre><ul><li>.then() is like “what to do when it works”</li><li>.catch() is like “what to do if it fails”</li><li>.finally() is like “jo bhi ho, ye toh karna hi hai”</li></ul><h3>🧩 Real-Life Example: Simulate API Call</h3><pre>function fetchData() {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      const data = { user: &quot;Amandeep&quot;, id: 1 };<br>      resolve(data);<br>    }, 2000);<br>  });<br>}<br><br>fetchData()<br>  .then((res) =&gt; console.log(&quot;Data:&quot;, res))<br>  .catch((err) =&gt; console.error(&quot;Error:&quot;, err));</pre><blockquote>🧠 Simulating an API call with<em> </em><em>setTimeout </em>– notice the async nature!</blockquote><h3>🧟 Callback Hell vs Promises</h3><p>Before Promises:</p><pre>getUser((user) =&gt; {<br>  getPosts(user, (posts) =&gt; {<br>    getComments(posts, (comments) =&gt; {<br>      console.log(comments);<br>    });<br>  });<br>});</pre><blockquote>💀<em> </em><strong>Callback Hell</strong><em>*: a pyramid of doom!*</em></blockquote><p>With Promises:</p><pre>getUser()<br>  .then(getPosts)<br>  .then(getComments)<br>  .then(console.log)<br>  .catch(console.error);</pre><blockquote>🎉 Much cleaner, and easier to debug!</blockquote><h3>🔗 Chaining Promises</h3><pre>new Promise((resolve) =&gt; resolve(5))<br>  .then((val) =&gt; val * 2) // 10<br>  .then((val) =&gt; val + 1) // 11<br>  .then(console.log);     // logs 11</pre><blockquote>Each<em> </em><em>.then() </em>gets the value from the previous one. It&#39;s like a relay race 🏃‍♂️🏃‍♂️🏃‍♂️</blockquote><h3>🤯 Common Mistake: Forgetting to Return</h3><pre>doSomething()<br>  .then((res) =&gt; {<br>    doSomethingElse(res); // ❌ returns undefined<br>  })<br>  .then((res) =&gt; {<br>    // &#39;res&#39; is undefined!<br>  });</pre><p>✅ Fix:</p><pre>doSomething()<br>  .then((res) =&gt; {<br>    return doSomethingElse(res); // ✅ return the next promise<br>  })<br>  .then((res) =&gt; {<br>    // &#39;res&#39; has correct value now<br>  });</pre><h3>🧠 Promise.all – Run Multiple in Parallel</h3><pre>Promise.all([<br>  fetchUser(),<br>  fetchPosts(),<br>  fetchComments(),<br>]).then(([user, posts, comments]) =&gt; {<br>  console.log({ user, posts, comments });<br>});</pre><ul><li>Waits for <strong>all</strong> Promises to resolve.</li><li>Fails fast if <strong>any</strong> one fails.</li></ul><h3>🕵️‍♂️ Promise.race – First to Finish Wins</h3><pre>Promise.race([<br>  slowNetworkCall(),<br>  timeout(3000),<br>]).then(console.log);</pre><ul><li>Returns the result of the <strong>first settled</strong> promise.</li><li>Use for <strong>timeouts</strong> or fallback strategies.</li></ul><h3>🧨 Promise.reject() and Promise.resolve()</h3><p>Create immediate Promises for testing or defaults:</p><pre>Promise.resolve(&quot;Instant value&quot;);<br>Promise.reject(&quot;Instant error&quot;);</pre><h3>🧙 Async/Await — The Promise Superpower</h3><pre>async function getData() {<br>  try {<br>    const user = await fetchUser();<br>    const posts = await fetchPosts(user.id);<br>    console.log(posts);<br>  } catch (err) {<br>    console.error(&quot;Oops!&quot;, err);<br>  }<br>}</pre><ul><li>Makes async code look synchronous 😍</li><li>Under the hood? Still uses Promises!</li></ul><blockquote>💡 Think of<em> </em><em>async/await </em>as<em> sugar </em>on top of Promises 🍭</blockquote><h3>🧶 Final Meme</h3><blockquote><em>When you finally master Promises and your async code works like butter*<br>“Arrey maza aa gaya!” 😎*</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f628d1d625" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Optimize Image Loading in React Like a Pro — Stop Killing Your Page Speed! ⚡]]></title>
            <link>https://aman-deepsingh.medium.com/%EF%B8%8F-optimize-image-loading-in-react-like-a-pro-stop-killing-your-page-speed-9f14fc9a9398?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f14fc9a9398</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[largest-contentful-paint]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[page-speed-optimization]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 08:47:26 GMT</pubDate>
            <atom:updated>2025-07-27T08:47:26.491Z</atom:updated>
            <content:encoded><![CDATA[<h3>🖼️ Optimize Image Loading in React Like a Pro — Stop Killing Your Page Speed! ⚡</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHmt6fu4lxs9y6nNC0T6ig.jpeg" /></figure><p>Let’s be honest:<br> Images are the <strong>heaviest</strong> thing on most websites.<br> And if not handled well, they’ll tank your <strong>performance</strong>, kill your <strong>SEO</strong>, and scare off your users 😱.</p><blockquote><em>“React is fast!”<br> Your 5MB PNG image: </em><strong><em>“Hold my bandwidth”</em></strong><em> 🐌</em></blockquote><p>So let’s fix that. Here’s how to <strong>optimize image loading in React apps</strong>, the smart way.</p><h3>🚀 Why Image Optimization Matters</h3><ul><li>✅ Faster load time = better UX</li><li>✅ Better Core Web Vitals (LCP especially)</li><li>✅ Better SEO ranking</li><li>✅ Lower bounce rate</li><li>✅ More conversions 💰</li></ul><h3>🔧 1. Use the Right Image Format</h3><h3>📦 Use modern formats:</h3><ul><li>WebP: Great balance between quality &amp; size</li><li>AVIF: Even smaller than WebP, but less supported</li><li>SVG: For icons and illustrations (resolution-independent)</li></ul><pre>&lt;img src=&quot;/image.webp&quot; alt=&quot;Optimized image&quot; /&gt;</pre><blockquote><em>⚠️ Avoid raw </em><em>.png or </em><em>.jpg if possible unless necessary.</em></blockquote><h3>🪄 2. Lazy Loading Images</h3><p>Only load images <strong>when they enter the viewport</strong>. Saves tons of bandwidth!</p><h3>✅ Native loading=&quot;lazy&quot;:</h3><pre>&lt;img src=&quot;/hero.webp&quot; loading=&quot;lazy&quot; alt=&quot;Hero image&quot; /&gt;</pre><h3>⚛️ Or use react-lazyload:</h3><pre>npm install react-lazyload</pre><pre>import LazyLoad from &quot;react-lazyload&quot;;</pre><pre>&lt;LazyLoad height={200} once&gt;<br>  &lt;img src=&quot;/banner.webp&quot; alt=&quot;Banner&quot; /&gt;<br>&lt;/LazyLoad&gt;</pre><blockquote><em>🧠 Tip: Wrap your images in </em><em>&lt;picture&gt; tags for responsive format switching too.</em></blockquote><h3>📏 3. Resize Images Properly</h3><p>Don’t load a 3000x2000 image into a 300x200 pixel space.</p><blockquote><em>“Why use a bazooka to kill a mosquito?” — Every browser ever.</em></blockquote><p>Use image compression tools or services like:</p><ul><li><a href="https://squoosh.app/">Squoosh</a></li><li><a href="https://tinypng.com/">TinyPNG</a></li><li><a href="https://cloudinary.com/">Cloudinary</a></li></ul><h3>💡 4. Use Responsive Images</h3><p>Use srcSet and sizes so browsers can choose the best version based on screen size:</p><pre>&lt;img<br>  src=&quot;/banner-480.jpg&quot;<br>  srcSet=&quot;/banner-480.jpg 480w, /banner-800.jpg 800w&quot;<br>  sizes=&quot;(max-width: 600px) 480px, 800px&quot;<br>  alt=&quot;Responsive Banner&quot;<br>/&gt;</pre><h3>🧠 5. Use the Image Component in Next.js</h3><p>If you’re using Next.js — this is gold. ✨</p><pre>import Image from &quot;next/image&quot;;</pre><pre>&lt;Image<br>  src=&quot;/hero.jpg&quot;<br>  width={800}<br>  height={600}<br>  alt=&quot;Hero&quot;<br>  priority // for above-the-fold<br>  quality={75}<br>  placeholder=&quot;blur&quot;<br>/&gt;</pre><p>✅ Features:</p><ul><li>Auto lazy-loading</li><li>Auto resizing &amp; optimization</li><li>Placeholder blur effect</li><li>WebP support</li><li>Loads only when needed</li></ul><blockquote><em>Next.js team be like: </em>“Let us do the image stuff so you can chill 😎”</blockquote><h3>🪞 6. Blur-Up Placeholder (Low Quality Image Preview — LQIP)</h3><p>Show a <strong>blurry low-res version</strong> while high-res loads.</p><h3>With next/image:</h3><pre>&lt;Image<br>  src=&quot;/beach.jpg&quot;<br>  alt=&quot;Beach&quot;<br>  placeholder=&quot;blur&quot;<br>  blurDataURL=&quot;/tiny-blur.jpg&quot;<br>/&gt;</pre><h3>Or manually:</h3><ul><li>Use a base64 image as a placeholder</li><li>CSS trick:</li></ul><pre>.image-blur {<br>  filter: blur(20px);<br>  transition: filter 0.3s ease;<br>}</pre><h3>🌐 7. Use a CDN for Images</h3><p>Instead of /public, use a <strong>Content Delivery Network</strong> like:</p><ul><li>Cloudinary</li><li>ImageKit</li><li>Vercel (for Next.js)</li><li>Firebase Storage</li></ul><pre>&lt;img src=&quot;https://cdn.myapp.com/img1.webp&quot; alt=&quot;CDN image&quot; /&gt;</pre><blockquote><em>This ensures images are served from the server </em><strong><em>closest</em></strong><em> to your user.</em></blockquote><h3>🔁 8. Preload Critical Images</h3><p>For above-the-fold images like hero banners:</p><pre>&lt;link rel=&quot;preload&quot; as=&quot;image&quot; href=&quot;/hero.webp&quot; /&gt;</pre><p>This tells the browser:<br> <em>“Hey, I’ll need this image really soon — don’t be lazy.”</em></p><h3>⚠️ 9. Avoid Background Images for Critical Content</h3><p>If your hero image is in CSS like this:</p><pre>.hero {<br>  background-image: url(https://medium.com/&#39;/bg.webp&#39;);<br>}</pre><p>…it won’t be preloaded or lazy-loaded efficiently.<br> Instead, use &lt;img&gt; or &lt;Image&gt; inside HTML/JSX.</p><h3>✅ Summary — Image Optimization Checklist 📝</h3><p>Optimization Done? ✅ <br>Use modern formats (WebP, AVIF) ✅ <br>Compress before upload ✅<br>Use lazy loading (loading=&quot;lazy&quot;) ✅ <br>Use responsive srcSet images ✅<br>Serve via CDN ✅ <br>Blur placeholders for UX ✅ <br>Don’t stretch full-res images ✅ <br>Prefer &lt;img&gt; over CSS backgrounds ✅ <br>Use Next.js Image if applicable ✅</p><h3>🎯 Final Meme</h3><blockquote>When Lighthouse gives you 100 on performance after optimizing images…<em><br>“Toh kaise lage hum?”</em></blockquote><h3>🧶 Wrapping Up</h3><p>Images are powerful — they tell stories, showcase products, and make your UI pop.<br> But if left unoptimized, they’ll drag your performance into the ground.</p><p>With just a few smart moves — lazy loading, compression, responsive formats — you can build <strong>fast, beautiful React apps</strong> that even Google will love 😍</p><h3>💬 Your Turn</h3><p>Got an image horror story or a go-to tool for compression?<br> Drop a comment, and let’s help each other make the web faster 💨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f14fc9a9398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ useState in React – The OG Hook That Started It All ]]></title>
            <link>https://aman-deepsingh.medium.com/usestate-in-react-the-og-hook-that-started-it-all-25c07fad2390?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/25c07fad2390</guid>
            <category><![CDATA[react-hook-usestate]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 08:25:56 GMT</pubDate>
            <atom:updated>2025-07-27T08:25:56.657Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHmt6fu4lxs9y6nNC0T6ig.jpeg" /></figure><p>React Hooks came in like a wrecking ball in v16.8, and leading the charge was our hero: <strong>useState</strong>.</p><p>It’s simple, powerful, and often misunderstood. Like a Bollywood hero in a 90s movie. 🎬💥</p><h3>🪝 What is useState?</h3><p>In one line:</p><blockquote><em>useState lets you add state to your functional components.</em></blockquote><p>Or in React’s own words: “Wanna make your component <em>remember stuff</em>? Use useState.”</p><h3>🧠 Without state:</h3><pre>function Counter() {<br>  let count = 0;<br>  return &lt;button onClick={() =&gt; count++}&gt;Click me&lt;/button&gt;;<br>}</pre><p>😐 Nothing happens. Because React doesn’t <em>remember</em> count.</p><h3>✅ With useState:</h3><pre>import { useState } from &quot;react&quot;;</pre><pre>function Counter() {<br>  const [count, setCount] = useState(0);</pre><pre>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      You clicked {count} times<br>    &lt;/button&gt;<br>  );<br>}</pre><p>🎉 Now React re-renders and remembers the new count every time you click!</p><h3>⚙️ The Syntax</h3><pre>const [state, setState] = useState(initialValue);</pre><p>📦 state: current value<br> 🔧 setState: function to update the value<br> 🎁 initialValue: the default (initial) state</p><h3>🧪 Real Life Example — A Like Button ❤️</h3><pre>function LikeButton() {<br>  const [liked, setLiked] = useState(false);<br>  return (<br>      &lt;button onClick={() =&gt; setLiked(!liked)}&gt;<br>        {liked ? &quot;💖 Liked&quot; : &quot;🤍 Like&quot;}<br>      &lt;/button&gt;<br>    );<br>  }</pre><p>🧠 Tip: Never update state directly like liked = true – always use setLiked.</p><h3>🧠 State is Async (kinda)</h3><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br>  const handleClick = () =&gt; {<br>      setCount(count + 1);<br>      console.log(count); // 😱 Still old value!<br>    };<br>    return &lt;button onClick={handleClick}&gt;Click&lt;/button&gt;;<br>  }</pre><p>Why? Because React <em>batches</em> updates and re-renders <strong>after</strong> the event handler.</p><h3>✅ Solution: Use Functional Update When Needed</h3><pre>setCount(prevCount =&gt; prevCount + 1);</pre><p>Why? Because sometimes you’re updating <strong>based on the old state</strong>.</p><blockquote>When you try setCount(count + 1) twice in a row and it only increases by 1<em><br> 🧠 “State updates are async, bro”</em></blockquote><h3>🧺 Example: Managing Multiple States</h3><pre>function ProfileForm() {<br>  const [name, setName] = useState(&quot;&quot;);<br>  const [age, setAge] = useState(&quot;&quot;);<br>  return (<br>      &lt;&gt;<br>        &lt;input value={name} onChange={(e) =&gt; setName(e.target.value)} /&gt;<br>        &lt;input value={age} onChange={(e) =&gt; setAge(e.target.value)} /&gt;<br>      &lt;/&gt;<br>    );<br>}</pre><p>Or use an object for grouped state:</p><pre>const [profile, setProfile] = useState({ name: &quot;&quot;, age: &quot;&quot; });<br>&lt;input<br>  value={profile.name}<br>  onChange={(e) =&gt; setProfile({ ...profile, name: e.target.value })}<br>/&gt;</pre><p>📛 <strong>Warning</strong>: Always spread the previous state to avoid wiping out other fields.</p><h3>🧹 Don’t Confuse with Variables</h3><p>This doesn’t work:</p><pre>let count = 0;<br>const handleClick = () =&gt; {<br>  count++;<br>};</pre><p>React doesn’t track normal variables. Only <strong>state updates</strong> cause re-renders.</p><blockquote>You changed a variable but nothing updated<em><br> </em><strong><em>React:</em></strong><em> “Main kya karun, job chhod du?” 😆</em></blockquote><h3>🎓 Bonus: Lazy Initialization</h3><pre>const [expensiveState, setExpensiveState] = useState(() =&gt; {<br>  console.log(&quot;Only runs once!&quot;);<br>  return computeExpensiveStuff();<br>});</pre><p>Useful if initialValue is heavy to compute – React will only call it <strong>once</strong>.</p><h3>💡 Tips</h3><p>✅ Use one state per concern<br> ✅ Use functional update when relying on old state<br> ❌ Don’t mutate state directly<br> ❌ Don’t read updated state right after calling setState</p><h3>🔚 Wrapping Up</h3><p>useState is like Maggie noodles 🍜 — easy to make, but mess it up and it’s a disaster!</p><p>Use it wisely and you can make your UI interactive, dynamic, and… well, alive 💡</p><blockquote><strong><em>When you finally understand </em></strong><strong><em>useState<br></em></strong>“Maa, main React samajh gaya!”</blockquote><h3>💬 Over to You</h3><p>What’s your favorite useState bug story? Drop a comment or meme below ⬇️<br> And if you enjoyed this, don’t forget to ❤️ the post and share it with your dev friends!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25c07fad2390" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Demystifying useEffect in React.js – The Sidekick You Never Knew You Needed ‍♂️]]></title>
            <link>https://aman-deepsingh.medium.com/demystifying-useeffect-in-react-js-the-sidekick-you-never-knew-you-needed-%EF%B8%8F-3006cadf88d7?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3006cadf88d7</guid>
            <category><![CDATA[data-fetching]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[react-hook-useeffect]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 08:08:18 GMT</pubDate>
            <atom:updated>2025-07-27T08:08:18.954Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHmt6fu4lxs9y6nNC0T6ig.jpeg" /></figure><p>Ah, useEffect. The one hook that either makes you feel like a <strong>React wizard 🧙‍♂️</strong> or makes you want to throw your laptop out the window 💻🚀.</p><p>Let’s break it down, desi-style, meme-style, and code-style. Buckle up! 🎢</p><h3>🧠 What is useEffect?</h3><p>In simple terms: <strong><em>useEffect lets you run some code (a side-effect) after your component renders.</em></strong></p><p>Imagine your React component is a movie 🎬. Rendering is the scene. useEffect is the <em>background music</em> or <em>after-credits scene</em> — something that happens alongside the main act.</p><h3>🤷‍♂️ Why do we need it?</h3><p>React is declarative. But what if you want to do things like:</p><ul><li>Fetch data from an API 🌐</li><li>Set up a subscription 🧷</li><li>Add event listeners (like a scroll or resize) 🖱️</li><li>Update the DOM manually (rare, but hey… it happens) 💪</li></ul><p>That’s where useEffect comes in.</p><h3>⚙️ Basic Syntax</h3><pre>import { useEffect } from &quot;react&quot;;</pre><pre>useEffect(() =&gt; {<br>  // your side-effect logic<br>});</pre><p>By default, it runs <strong>after every render</strong> (yes, every 😩). But don’t worry, we’ll fix that.</p><h3>🧪 Example 1: Console.log on Every Render</h3><pre>import { useEffect, useState } from &quot;react&quot;;</pre><pre>function LoggerComponent() {<br>  const [count, setCount] = useState(0);</pre><pre>  useEffect(() =&gt; {<br>    console.log(&quot;Component rendered! 🔁&quot;);<br>  });</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;You clicked {count} times.&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Click me!&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>📌 Every time you click, useEffect runs.</p><h3>🧯 Example 2: Run Only Once (on Mount)</h3><p>Just like componentDidMount in class components.</p><pre>useEffect(() =&gt; {<br>  console.log(&quot;Component mounted! 🚀&quot;);<br>}, []); // empty dependency array</pre><p>✅ It runs only once when the component loads.</p><h3>🔁 Example 3: Run When a Value Changes</h3><pre>useEffect(() =&gt; {<br>  console.log(&quot;Count changed:&quot;, count);<br>}, [count]); // runs only when &#39;count&#39; changes</pre><p>Think of this like saying:</p><blockquote><em>“Hey React, only run this if </em><em>count has changed, okay?&quot;</em></blockquote><h3>🧹 Example 4: Cleanup on Unmount</h3><p>Perfect for things like removing event listeners or cancelling timers.</p><pre>useEffect(() =&gt; {<br>  const interval = setInterval(() =&gt; {<br>    console.log(&quot;Tick ⏱️&quot;);<br>  }, 1000);</pre><pre>  return () =&gt; {<br>    clearInterval(interval);<br>    console.log(&quot;Cleanup done 🧼&quot;);<br>  };<br>}, []);</pre><p>🧼 The return function is the cleanup — React calls it when the component unmounts or before re-running the effect.</p><h3>🧠 Mind = Blown: Dependency Gotchas 😵</h3><p>Let’s say you’re fetching data based on id prop:</p><pre>useEffect(() =&gt; {<br>  fetch(`/api/user/${id}`).then(...);<br>}, [id]);</pre><p>✅ Good: only fetches when id changes.</p><p>🚨 Bad: if you forget [id], it&#39;ll run on every render.</p><h3>🧙‍♂️ Golden Rules of useEffect</h3><ol><li>Always add dependencies you use inside the effect.</li><li>Use multiple useEffects for unrelated logic.</li><li>Avoid putting async functions directly in useEffect (wrap them inside).</li></ol><pre>useEffect(() =&gt; { <br>  <br>  async function fetchData() {     <br>    const res = await fetch(...);   <br>  }   <br>  fetchData(); <br><br>}, []);</pre><h3>🧠 Real-World Example: Fetching Data</h3><pre>function UserProfile({ userId }) {<br><br>  const [user, setUser] = useState(null);<br><br>  useEffect(() =&gt; {<br><br>    let isMounted = true;<br><br>    async function fetchUser() {<br><br>      const res = await fetch(`/api/user/${userId}`);<br>      const data = await res.json();<br>      if (isMounted) setUser(data);<br><br>    }<br><br>    fetchUser();<br><br>    return () =&gt; {<br>      isMounted = false; // prevent state updates if unmounted<br>    };<br><br>  }, [userId]);<br><br>  if (!user) return &lt;p&gt;Loading...&lt;/p&gt;;<br><br>  return &lt;div&gt;Hello, {user.name} 👋&lt;/div&gt;;<br>}</pre><h3>TL;DR</h3><ul><li>useEffect(() =&gt; {}, []) = run once.</li><li>useEffect(() =&gt; {}, [value]) = run when value changes.</li><li>useEffect(() =&gt; { return () =&gt; {} }) = cleanup.</li><li>Always handle async stuff carefully 🧠.</li></ul><h3>🧶 Wrapping Up</h3><p>useEffect is powerful. But with great power comes... yep, great responsibility 🕸️.</p><p>Use it wisely. Split your concerns. Don’t fear the dependency array — embrace it.</p><p>If you found this helpful (or at least mildly entertaining 😄), share it with your React buddies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3006cadf88d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aman Paaji From Intern to SDE-III: My Journey in 3 Years (and Counting…)]]></title>
            <link>https://aman-deepsingh.medium.com/aman-paaji-from-intern-to-sde-iii-my-journey-in-3-years-and-counting-383475c3651d?source=rss-f11327daa55a------2</link>
            <guid isPermaLink="false">https://medium.com/p/383475c3651d</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[journey]]></category>
            <category><![CDATA[success]]></category>
            <category><![CDATA[achievement]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Amandeep Singh]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 10:17:25 GMT</pubDate>
            <atom:updated>2025-07-17T10:17:25.860Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey everyone! 👋<br> I’m <strong>Amandeep Singh</strong>, a frontend developer who loves turning designs into delightful web experiences. Today, I’m finally doing something I’ve wanted to do for a long time — starting my journey of <strong>sharing knowledge and stories</strong> through writing.</p><p>And what better way to begin than by sharing a bit about <strong>me and my journey</strong> so far? Buckle up, it’s been quite a ride! 😄</p><h3>👨‍💻 How It All Started…</h3><p>Back in 2018, I took my first real step into tech by joining <strong>Visvesvaraya Technological University</strong>, majoring in Computer Science. I was just a regular guy trying to figure out pointers in C++ and praying my code compiled before the lab deadline. 🧑‍💻😅</p><p>By 2022, I was lucky enough to land an <strong>internship at Zolostays</strong>, a fast-moving tech company in the co-living space. What started as an internship soon turned into a full-time role, and within <strong>3 years</strong>, I moved up from <strong>SDE Intern → SDE I → SDE II → SDE III</strong>. 🚀</p><h3>🏗️ What I Built (And Broke… Then Fixed 😅)</h3><p>At Zolostays, I got to work on <strong>real stuff</strong>. I’m talking:</p><ul><li>Building luxury stay websites like <a href="https://z.vacations/">z.vacations</a> using <strong>Next.js</strong>, <strong>Tailwind</strong>, and <strong>Framer Motion</strong> ✨</li><li>Creating high-converting landing pages that boosted lead conversions by <strong>30%</strong> 📈</li><li>Revamping the whole <a href="https://zolostays.com/">zolostays.com</a> website for performance + SEO, bringing in <strong>40% more organic traffic</strong></li><li>Migrating legacy AngularJS CRM modules to <strong>Next.js</strong> (trust me, it was a game-changer for our support team)</li><li>Speeding up our CI/CD pipelines and page loads using <strong>Docker</strong>, <strong>CDNs</strong>, and analytics integrations 💡</li></ul><p>Basically, if it had a screen, a DOM, and users — I wanted to improve it. 💪</p><h3>🎮 Side Projects &amp; Fun Stuff</h3><p>I’m a massive fan of <strong>Kaun Banega Crorepati</strong> (who isn’t?!), so I built my own quiz app called <a href="https://amandeep-kbc.netlify.app/">KBC Web App</a> using React. 📺🧠<br> It was fun, frustrating, and super rewarding. You can check out the code <a href="https://github.com/Amandeep-tech/kbc-react">here</a>.</p><p>I’ve also contributed to <a href="https://leetcode.com/contribute/23862">LeetCode</a> (yep, I created a question!) and enjoyed competing in coding events — even bagging <strong>2nd</strong> place in a C++ quiz and <strong>4th</strong> in an IISC Bangalore coding comp! 🏆</p><h3>🧠 What I’ve Learned So Far</h3><ul><li><strong>Code is not just syntax</strong> — it’s communication with future developers (including future-you 😅)</li><li><strong>Frontend is a superpower</strong> — You literally control how users experience your brand.</li><li><strong>Performance + UX + SEO = 🔥</strong> — Balancing these is hard, but magical when it clicks.</li><li>And most importantly: <strong>Consistency &gt; Talent</strong>. Show up, build stuff, break stuff, learn, repeat.</li></ul><h3>🛠️ What’s Next?</h3><p>This Medium blog is my way of giving back to the community that taught me <strong>everything</strong> via blogs, tutorials, GitHub, and StackOverflow. 💖</p><p>I’ll be sharing:</p><ul><li>Frontend deep dives (React, Next.js, Tailwind, performance tricks)</li><li>Dev life lessons and productivity hacks</li><li>Side projects &amp; open-source learnings</li><li>Maybe even a few tech memes 🤓</li></ul><p>So if you’re into <strong>frontend tech, learning, or just vibing with another dev on the internet</strong>, hit that follow button ❤️</p><h3>🌐 Let’s Connect!</h3><p>📍 <a href="https://singhamandeep.dev/">Portfolio</a><br> 💼 <a href="https://linkedin.com/in/amandeep-singh-9241061a6">LinkedIn</a><br> 💻 <a href="https://github.com/Amandeep-tech">GitHub</a><br> 📬 <a href="/service/mailto:amanpank8910@gmail.com">Email</a></p><p>Thanks for reading this far 🙌<br> If you’ve just started out, keep going. If you’re stuck, keep learning. And if you’re ahead — help someone out. That’s how we grow. 💙</p><p><strong>See you in the next post! 👋</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383475c3651d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>