<?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 Rajat Singh on Medium]]></title>
        <description><![CDATA[Stories by Rajat Singh on Medium]]></description>
        <link>https://medium.com/@iamrajatsingh?source=rss-cc710fb5c0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sfsQfHNT8J8was_rPYjUhA.png</url>
            <title>Stories by Rajat Singh on Medium</title>
            <link>https://medium.com/@iamrajatsingh?source=rss-cc710fb5c0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:09:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamrajatsingh/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[Micro-Frontends Architecture: Lessons from Building Domain-Driven Frontend Systems in Fintech &…]]></title>
            <link>https://iamrajatsingh.medium.com/micro-frontends-architecture-lessons-from-building-domain-driven-frontend-systems-in-fintech-f284b77a4f8b?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f284b77a4f8b</guid>
            <category><![CDATA[frontend-system-design]]></category>
            <category><![CDATA[micro-frontend-deployment]]></category>
            <category><![CDATA[microfrontend-vs-monolith]]></category>
            <category><![CDATA[implement-microfrontend]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 17:43:57 GMT</pubDate>
            <atom:updated>2026-02-06T17:43:57.688Z</atom:updated>
            <content:encoded><![CDATA[<h3>Micro-Frontends Architecture: Lessons from Building Domain-Driven Frontend Systems in Fintech &amp; Trading</h3><h3>🚀 Introduction</h3><p>As frontend applications scale, they often become difficult to maintain, risky to deploy, and tightly coupled across teams. What starts as a simple SPA slowly turns into a massive codebase where even small UI changes require coordination across multiple teams.</p><p>To solve this, many large engineering organizations — especially in fintech and trading — are adopting <strong>Micro-Frontends Architecture</strong>.</p><p>This article explains:</p><ul><li>What micro-frontends are ?</li><li>Why they exist ?</li><li>How they work ?</li><li>What we learned implementing them in real fintech / trading UI systems ?</li></ul><h3>🧩 What Are Micro-Frontends?</h3><p>Micro-frontends are an architectural pattern where a frontend is split into <strong>smaller, independently developed and deployed applications</strong>, composed together to form one product experience.</p><p>Instead of:</p><pre>One Large Frontend App</pre><p>You build:</p><pre>Auth + Trading + Portfolio + Analytics + Shared Design System</pre><p>Each domain can evolve and deploy independently.</p><h3>🏗 High-Level Micro-Frontend Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmK6KEgAwH8iQBFN-d7A3g.png" /></figure><h3>Typical structure:</h3><h4>Shell Application</h4><p>Handles:</p><ul><li>Routing</li><li>Layout</li><li>Auth bootstrap</li><li>Global theme</li></ul><h4>Micro Apps</h4><p>Handle:</p><ul><li>Domain logic</li><li>UI + state</li><li>Domain APIs</li><li>Independent deployments</li></ul><h3>🤔 Why Micro-Frontends Exist</h3><p>At scale, frontend problems become <strong>organizational problems</strong>.</p><p>Common pain points:</p><ul><li>Slow release cycles</li><li>Cross-team merge conflicts</li><li>Risky production deployments</li><li>Difficult framework upgrades</li><li>Tight coupling between domains</li></ul><p>Micro-frontends introduce <strong>domain isolation in UI</strong>.</p><h3>⚙️ Runtime Flow (How Apps Load)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cyqJ6ii1Q_fnvZdW.jpeg" /></figure><p>Example runtime flow:</p><pre>User opens → /trade/orders<br>Shell loads → Trading Micro App<br>Trading renders → Inside Shell Layout</pre><h3>🏦 What We Learned Building Domain-Driven Frontend in Fintech / Trading</h3><p>This is where theory meets reality.</p><p>Trading systems are different from typical SaaS:</p><ul><li>Real-time data streams</li><li>Strict reliability requirements</li><li>Complex user workflows</li><li>Regulatory constraints</li></ul><h3>🧭 1. Domain Boundaries Must Follow Business Workflows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*jW-rIdS_15Lr4-UL.png" /></figure><p>❌ Wrong Split:</p><pre>Orders Page<br>Charts Page<br>Holdings Page</pre><p>✅ Correct Split:</p><pre>Trading Domain<br>Portfolio Domain<br>Market Data Domain<br>Auth Domain</pre><p>Why:<br>Trading workflows span multiple screens — domain boundaries should follow business capabilities.</p><h3>⚡ 2. Real-Time Data Changes Everything</h3><p>In trading UI:</p><ul><li>Market ticks update every second</li><li>Orders update portfolio instantly</li><li>Risk changes margin availability live</li></ul><p>What worked well:</p><ul><li>Single shared market data connection</li><li>Event bus / pub-sub between domains</li><li>Avoid multiple WebSocket connections per micro-app</li></ul><h3>🧱 3. Keep the Shell Extremely Thin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*DT_QaQrzZs4FJNLr.png" /></figure><p>Shell should handle:<br>✔ Routing<br>✔ Layout<br>✔ Auth bootstrap<br>✔ Theme</p><p>Shell should NOT handle:<br>✖ Trading logic<br>✖ Portfolio calculations<br>✖ Domain APIs</p><p>If it does → you rebuild a frontend monolith.</p><h3>🔐 4. Auth and Permissions Are More Complex in Fintech</h3><p>Not just login.</p><p>You must support:</p><ul><li>Trading permissions</li><li>Segment restrictions</li><li>Compliance flags</li><li>Session expiry safety</li></ul><p>Best approach:</p><ul><li>Shared auth context globally</li><li>Domain-level authorization rules locally</li></ul><h3>📦 5. Shared Design System Is Mandatory</h3><p>Without shared UI:</p><ul><li>Visual drift happens fast</li><li>Accessibility breaks</li><li>Performance becomes inconsistent</li></ul><p>Trading users rely heavily on UI consistency and speed perception.</p><h3>🚨 6. Independent Deployment Requires Strong Contracts</h3><p>If Trading changes API shape → Portfolio may silently break.</p><p>Must have:</p><ul><li>API schemas</li><li>Contract tests</li><li>Versioned APIs</li></ul><h3>📉 7. Performance Needs Active Management</h3><p>Common risks:</p><ul><li>Duplicate React bundles</li><li>Duplicate charting libraries</li><li>Large vendor bundles</li></ul><p>Fix:</p><ul><li>Shared dependency federation</li><li>Lazy domain loading</li><li>Preload critical trading flows</li></ul><h3>👥 8. Team Structure Matters More Than Tools</h3><p>Best pattern:</p><pre>Platform Team → Shell + Infra + Design System<br>Domain Teams → Trading / Portfolio / Market Data</pre><p>Architecture fails when ownership is unclear.</p><h3>🧠 Biggest Realization</h3><p>In fintech, micro-frontends are less about frontend frameworks and more about:</p><p>👉 Risk isolation<br>👉 Deployment safety<br>👉 Real-time coordination<br>👉 Regulatory stability</p><h3>🎯 When You Should Use Micro-Frontends</h3><p>Use when:</p><ul><li>Multiple frontend teams exist</li><li>Domains are clearly separable</li><li>Frequent deployments required</li><li>Platform will scale long-term</li></ul><p>Avoid when:</p><ul><li>Small team</li><li>Early product stage</li><li>Low deployment frequency</li></ul><h3>🏁 Final Thoughts</h3><p>Micro-frontends are not just a frontend pattern — they are an <strong>organizational scaling strategy</strong>.</p><p>When applied correctly, they enable:</p><ul><li>Faster innovation</li><li>Safer releases</li><li>Clear ownership</li><li>Long-term scalability</li></ul><p>But when applied too early, they add unnecessary complexity.</p><p>The key is aligning architecture with <strong>business domain complexity</strong>, not just technology trends.</p><h3>📚 Architecture Series</h3><p>This article is part of a frontend architecture series:</p><p>1️⃣ Micro-Frontends Architecture — Concepts + Real Fintech Lessons <em>(You are here)</em><br> 2️⃣ Polyrepo vs Monorepo — Scaling Codebases for Large Engineering Teams <em>(coming soon)</em><br> 3️⃣ Single-SPA — Tooling Deep Dive for Micro-Frontend Orchestration <em>(coming soon)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f284b77a4f8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an Offline-First Web App That Automatically Syncs When Online]]></title>
            <link>https://iamrajatsingh.medium.com/how-to-build-an-offline-first-web-app-that-automatically-syncs-when-online-eced357c395a?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eced357c395a</guid>
            <category><![CDATA[web-browser]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[offline-first]]></category>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 12:46:58 GMT</pubDate>
            <atom:updated>2025-12-09T12:47:18.963Z</atom:updated>
            <content:encoded><![CDATA[<p>A Step-by-Step Guide to Building Reliable Apps That Work Even Without Internet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4aHbWCKDn3ZfXKbuKW9Vg.png" /></figure><p>We live in a world where users expect applications to <em>just work</em> — whether they’re in the office, on a train, or in a low-network zone. Yet most web apps still break the moment the internet does.</p><p>That’s where <strong>Offline-first design</strong> comes in. It’s not just a feature anymore — it’s becoming the default expectation.</p><p>In this article, we’ll walk through how you can build a web application (using React for examples) that continues to work even when offline and automatically syncs with the backend when it comes back online.</p><p>This is the same concept that powers apps like <strong>Google Docs, Notion, Linear</strong>, and modern CRM platforms.</p><p>Let’s break it down.</p><h3>🚨 The Problem: “No Internet” Should Not Mean “No App”</h3><p>Traditional web apps assume:</p><blockquote><em>“User clicks → call backend → show result.”</em></blockquote><p>But users often:</p><ul><li>Enter tunnels</li><li>Lose signal</li><li>Switch networks</li><li>Travel</li><li>Work in remote areas</li><li>Use restrictive enterprise WiFi</li></ul><p>And when that request fails, data is lost or workflows break.</p><p>This creates a terrible experience.</p><p>Offline-first fixes that.</p><h3>🎯 The Offline-First Goal</h3><p>An offline-capable app should:</p><ol><li><strong>Allow users to continue working offline</strong></li><li><strong>Store their actions locally</strong></li><li><strong>Detect when the device comes online</strong></li><li><strong>Automatically sync pending actions to the backend</strong></li><li><strong>Handle conflicts gracefully</strong></li></ol><p>This pattern is often called <strong>“offline action queueing”</strong>, and it’s the foundation of any reliable offline-first system.</p><h3>🧠 The Core Idea Behind Offline Sync</h3><p>At a high level, the flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jyZr5vn3ggqkEqy7ai4AA.png" /></figure><h3>1. User performs an action</h3><p>If online → send request normally<br> If offline → add request to a local queue</p><h3>2. Browser detects the “online” event</h3><p>Your app gets notified automatically.</p><h3>3. When internet returns</h3><p>Flush the queue → send all pending actions → clear queue only if successful</p><h3>4. If backend is temporarily down</h3><p>Retry again later (using backoff strategy).</p><p>This keeps your app responsive and prevents data loss.</p><h3>⚛️ A Simple React Example (Concept Only)</h3><p>Here’s a minimal version of how this works with React:</p><pre>function OfflineSyncComponent() {<br>  const [text, setText] = useState(&quot;&quot;);<br><br>  const syncToBackend = async (payload) =&gt;<br>    fetch(&quot;/api/save&quot;, { method: &quot;POST&quot;, body: JSON.stringify(payload) });<br><br>  const enqueue = (value) =&gt; {<br>    const queue = JSON.parse(localStorage.getItem(&quot;queue&quot;) || &quot;[]&quot;);<br>    queue.push(value);<br>    localStorage.setItem(&quot;queue&quot;, JSON.stringify(queue));<br>  };<br><br>  const flushQueue = async () =&gt; {<br>    const queue = JSON.parse(localStorage.getItem(&quot;queue&quot;) || &quot;[]&quot;);<br>    for (const item of queue) {<br>      try {<br>        await syncToBackend(item);<br>      } catch {<br>        return; // If sync fails, stop and retry later<br>      }<br>    }<br>    localStorage.removeItem(&quot;queue&quot;);<br>  };<br><br>  const handleSubmit = async () =&gt; {<br>    const payload = { text, timestamp: Date.now() };<br><br>    if (!navigator.onLine) {<br>      enqueue(payload);<br>    } else {<br>      try {<br>        await syncToBackend(payload);<br>      } catch {<br>        enqueue(payload);<br>      }<br>    }<br><br>    setText(&quot;&quot;);<br>  };<br><br>  useEffect(() =&gt; {<br>    const handler = () =&gt; {<br>      if (navigator.onLine) flushQueue();<br>    };<br><br>    window.addEventListener(&quot;online&quot;, handler);<br>    return () =&gt; window.removeEventListener(&quot;online&quot;, handler);<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Status: {navigator.onLine ? &quot;Online&quot; : &quot;Offline&quot;}&lt;/p&gt;<br>      &lt;input value={text} onChange={(e) =&gt; setText(e.target.value)} /&gt;<br>      &lt;button onClick={handleSubmit}&gt;Save&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This is not production-ready yet, but it demonstrates the core flow very clearly.</p><h3>🏗️ Taking This to Production</h3><p>A robust offline-first application includes more than just a local queue. Here’s what you’d typically add:</p><h3>1. Use IndexedDB instead of LocalStorage</h3><p>For performance, better write patterns, and large data handling.</p><h3>2. Use Service Workers for background sync</h3><p>The app continues syncing even when closed.</p><h3>3. Use Optimistic UI updates</h3><p>Make the app <em>feel</em> instant, and sync silently.</p><h3>4. Implement conflict resolution</h3><p>Especially when multiple users can edit the same record.</p><h3>5. Add retry strategies</h3><p>Exponential backoff, capped retries, intelligent grouping.</p><h3>6. Add a “Sync Status” indicator</h3><p>Great for user confidence and debugging.</p><p>With these pieces combined, you get a <strong>resilient, native-feeling</strong> web application.</p><h3>📦 Where Offline-First Apps Shine</h3><p>This pattern is extremely valuable in:</p><p>✔ Fintech apps (drafts, preferences, non-market operations)<br> ✔ CRM and sales apps used in the field<br> ✔ Logistics and inventory systems<br> ✔ Notes/task apps<br> ✔ Mobile-heavy applications<br> ✔ Any enterprise product used in low-network environments</p><p>Even if your app doesn’t need full offline mode, having failsafe sync logic dramatically improves the UX.</p><h3>🧩 Final Thoughts</h3><p>Offline-first isn’t just a fancy engineering idea — it’s a <strong>UX philosophy</strong>.</p><p>By temporarily decoupling the user’s actions from the backend’s availability, you make your application dramatically more resilient, reliable, and fast.</p><p>And once you’ve implemented the core offline-sync flow, you’ll wonder why most web apps don’t already work this way.</p><p>If you’re building modern, user-focused applications — especially in fintech, SaaS, CRM, or mobile-web — you should absolutely consider offline-first architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eced357c395a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[setTimeout: Powerful Web API]]></title>
            <link>https://iamrajatsingh.medium.com/settimeout-powerful-web-api-5a2661b64522?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a2661b64522</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 18:51:38 GMT</pubDate>
            <atom:updated>2026-03-02T17:30:46.582Z</atom:updated>
            <content:encoded><![CDATA[<h3>setTimeout: Powerful Web API &amp; Polyfill</h3><figure><img alt="A clock dial showcasing clock handles sweeping over time" src="https://cdn-images-1.medium.com/max/1024/0*yLBo8jOvugx7q0Gv" /><figcaption>Photo by <a href="https://unsplash.com/@agebarros?utm_source=medium&amp;utm_medium=referral">Agê Barros</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What is setTimeout ?</h4><p>setTimeout is a timer function provided by the runtime environment (such as the browser Web APIs or Node.js), allowing you to schedule execution of code after a specified delay (in milliseconds). It is commonly used to delay a piece of code or execute it asynchronously after a certain period.</p><p><strong>Syntax</strong></p><pre>setTimeout(callback, delay, ...args);</pre><p><strong>Parameters</strong></p><ol><li><strong>callback</strong> (required):The function to execute after the delay.</li><li><strong>delay</strong> (optional): The time in milliseconds to wait before executing the callback. Defaults to 0 if not provided.</li><li><strong>...args</strong> (optional): Arguments to pass to the callback function when it is executed.</li></ol><p><strong>Want to see how we can write a polyfill for it ? </strong>Let’s see.</p><h4>- Building it through setInterval</h4><pre>function setTimeoutPolyfill(callback, delay) {<br>  const start = Date.now() // Record the start time<br><br>  const intervalId = setInterval(() =&gt; {<br>    const elapsed = Date.now() - start // Calculate elapsed time<br><br>    if (elapsed &gt;= delay) {<br>      clearInterval(intervalId) // Clear the interval once delay has passed<br>      callback() // Execute the callback<br>    }<br>  }, 1) // Check every 1ms (smallest practical interval)<br>}<br><br><br>setTimeoutPolyfill(() =&gt; {<br>  console.log(&quot;Executed after 2000ms&quot;);<br>}, 2000);</pre><h4>- Building it from scratch</h4><pre>function createSetTimeout() {<br>  let timerId = 0<br>  let timerMap = {}<br><br>  function mySetTimeout(cb, time, ...args) {<br>    var id = timerId++<br>    timerMap[id] = true<br>    let start = Date.now()<br><br>    function triggerCallback() {<br>      if (!timerMap[id]) return<br>      if (Date.now() &gt; start + time) {<br>        cb.apply(this, args)<br>      } else {<br>        requestIdleCallback(triggerCallback)<br>      }<br>    }<br>    requestIdleCallback(triggerCallback)<br>    return id<br>  }<br><br>  function myClearTimeout(id) {<br>    delete timerMap[id]<br>  }<br>  return {<br>    mySetTimeout,<br>    myClearTimeout,<br>  }<br>}<br>const { mySetTimeout, myClearTimeout } = createSetTimeout()<br>let timer = mySetTimeout(<br>  (...args) =&gt; {<br>    console.log(&quot;this is setTimeout.....&quot;, ...args)<br>  },<br>  1000,<br>  &quot;Rajat&quot;,<br>  &quot;Singh&quot;,<br>)</pre><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a2661b64522" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polyfills in Javascript: What and Why ?]]></title>
            <link>https://iamrajatsingh.medium.com/polyfills-in-javascript-what-and-why-1b403b14d14f?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b403b14d14f</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascrıpt]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 19:28:17 GMT</pubDate>
            <atom:updated>2025-01-16T19:28:17.761Z</atom:updated>
            <content:encoded><![CDATA[<h3>Polyfills in Javascript: What &amp; Why ?</h3><figure><img alt="A small bridge over a river" src="https://cdn-images-1.medium.com/max/1024/0*nENcOQQGuDtWNVRG" /><figcaption>Polyfills bridging the gaps 👀</figcaption></figure><h3><strong>Understanding Polyfills in JavaScript</strong></h3><p>When developing modern JavaScript applications, ensuring compatibility across different browsers and environments is a common challenge. New features are frequently introduced in the language, but not all browsers or environments adopt them at the same pace. This is where <strong>polyfills</strong> come into play.</p><h3>What is Polyfill ?</h3><p>A <strong>polyfill</strong> is a piece of code (typically JavaScript) that provides modern functionality in older environments that do not natively support it. Polyfills essentially “<strong>fill in the gaps</strong>,” allowing developers to use new JavaScript methods or APIs while maintaining compatibility with older browsers.</p><p>In simpler terms, a polyfill implements a missing feature to mimic its behaviour as closely as possible.</p><h3>Why Use Polyfills?</h3><ol><li><strong>Cross-Browser Compatibility:</strong> Ensure your application works seamlessly across various browsers and environments, including older ones.</li><li><strong>Leverage Modern Features:</strong> Use the latest JavaScript methods or APIs without worrying about breaking your application for users with outdated browsers.</li><li><strong>Backward Compatibility:</strong> Maintain a consistent experience for all users, regardless of their browser version.</li></ol><h3>How Polyfills Work</h3><p>A polyfill checks if the desired feature exists in the current environment. If it doesn’t, the polyfill implements the feature using custom code.</p><h4>Example: Writing a Polyfill for Array.prototype.includes</h4><p>The Array.prototype.includes method checks if an array contains a specific value. This method might not be available in older browsers, so you could write a polyfill like this:</p><pre>if (!Array.prototype.includes) {<br>    Array.prototype.includes = function(valueToFind, fromIndex) {<br>        // If `fromIndex` is not provided, default to 0<br>        fromIndex = fromIndex || 0;<br>        // Ensure `fromIndex` is a valid index<br>        if (fromIndex &lt; 0) {<br>            fromIndex = Math.max(this.length + fromIndex, 0);<br>        }<br>        // Iterate through the array to check for the value<br>        for (let i = fromIndex; i &lt; this.length; i++) {<br>            if (this[i] === valueToFind) {<br>                return true;<br>            }<br>        }<br>        return false;<br>    };<br>}</pre><h4>How It Works</h4><ol><li>The polyfill first checks if Array.prototype.includes exists.</li><li>If it doesn’t, it defines the method.</li><li>The custom implementation ensures consistent behavior, including handling negative indices.</li></ol><h3>Key Characteristics of Polyfills</h3><ol><li><strong>Feature Detection:</strong> Polyfills check for the existence of a feature before providing their implementation.</li><li><strong>Non-Invasive:</strong> They only add functionality if it’s missing, ensuring that native implementations are not overridden.</li><li><strong>Lightweight:</strong> Most polyfills are focused on a single feature, keeping the code minimal and efficient.</li></ol><h3>When Should You Write Your Own Polyfill?</h3><p>Writing your own polyfill can be useful when:</p><ul><li>The <strong>feature</strong> you need isn’t supported in your target browsers.</li><li>An <strong>existing polyfill</strong> isn’t available or doesn’t meet your requirements.</li><li>You want to <strong>understand</strong> how the feature works under the hood.</li></ul><h3>Advantages of Using Polyfills</h3><ul><li><strong>Modern Development:</strong> Allows developers to use the latest features of JavaScript.</li><li><strong>Improved User Experience:</strong> Ensures a consistent and smooth experience across all platforms.</li><li><strong>Minimal Effort:</strong> Many polyfills are readily available in libraries like <a href="https://github.com/zloirock/core-js">core-js</a>.</li></ul><h3>Limitations of Polyfills</h3><ol><li><strong>Performance Overhead:</strong> Polyfills implemented in JavaScript can be slower than native functionality.</li><li><strong>Limited Scope:</strong> Some advanced APIs, especially those relying on hardware or low-level features, cannot be polyfilled effectively.</li><li><strong>Code Maintenance:</strong> Adding polyfills increases your codebase size and can introduce maintenance challenges.</li></ol><h3>Best Practices for Using Polyfills</h3><ol><li><strong>Feature Detection:</strong> Always check if a feature exists before applying a polyfill.</li><li><strong>Use Existing Libraries:</strong> Explore widely-used libraries like core-js or polyfill.io for reliable polyfills.</li><li><strong>Avoid Overuse:</strong> Only polyfill features that are essential for your application.</li><li><strong>Consider Alternatives:</strong> Tools like <strong>Babel</strong> can transpile modern JavaScript into backward-compatible code, reducing the need for polyfills.</li></ol><h3>Conclusion</h3><p>Polyfills are a powerful way to bridge the gap between modern JavaScript features and older browsers. By understanding how polyfills work and when to use them, you can create more robust and compatible applications. Whether you’re writing your own polyfill or using a library, they’re an essential tool for any developer looking to support a wide range of environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b403b14d14f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tanstack Query for state management]]></title>
            <link>https://iamrajatsingh.medium.com/tanstack-query-for-state-management-e37b467a82db?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e37b467a82db</guid>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 18:49:46 GMT</pubDate>
            <atom:updated>2025-01-16T18:49:46.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uv-2R_iazm19QVEB" /></figure><blockquote>TanStack Query, often referred to as React Query, is a powerful data-fetching and state management library for React applications. It simplifies data synchronization and handling of server state, providing developers with a set of tools to manage asynchronous operations effectively. Here are some key aspects of TanStack Query:</blockquote><ol><li><strong>Data Fetching:</strong><br>TanStack Query provides a declarative approach to fetching data, making it simple to define what data your components need and how to retrieve it. The library handles the fetching, caching, synchronization, and updating of data in your application.</li><li><strong>Caching:</strong><br>One of the standout features of TanStack Query is its caching mechanism. It intelligently caches data to avoid unnecessary network requests, which improves performance and reduces load on your servers. Cached data is automatically kept fresh and synchronized with the server.</li><li><strong>Mutations:<br></strong>TanStack Query offers robust support for mutations (operations that modify data, such as POST, PUT, DELETE requests). Mutations are handled in a way that ensures your UI remains responsive and provides options for optimistic updates, rollbacks, and retries.</li><li><strong>Automatic Background Refetching:<br></strong>The library can automatically refetch data in the background to keep it fresh. This is particularly useful for keeping your application state up-to-date without manual intervention.</li><li><strong>Query Keys:<br></strong>Queries are identified using query keys, which can be strings or arrays. Query keys allow you to uniquely identify and manage your queries, enabling fine-grained control over caching and refetching behaviors.</li><li><strong>DevTools:<br></strong>TanStack Query comes with a set of DevTools that can be integrated into your application to help debug and visualize the state of your queries and mutations. This is extremely useful during development for monitoring query states and understanding how data flows through your application.</li><li><strong>Server-Side Rendering (SSR) Support:<br></strong>For applications that require SSR, TanStack Query offers support to prefetch data on the server side, ensuring that the initial render has all the necessary data and improving the overall user experience.</li><li><strong>Custom Query Functions:<br></strong>TanStack Query is highly customizable, allowing you to define custom query and mutation functions. This flexibility ensures that it can be adapted to suit the specific needs and architecture of your application.</li><li><strong>Error Handling:<br></strong>It provides built-in error handling mechanisms, including retry logic and error boundaries. This ensures that your application can gracefully handle errors and provide a better user experience.</li><li><strong>Query Invalidation:<br></strong>Queries can be invalidated manually or automatically based on certain triggers. This means you can refresh specific parts of your application data when necessary, ensuring that users always see the most up-to-date information.</li></ol><h3><strong>Example Usage</strong></h3><p>Here’s a simple example to demonstrate how TanStack Query can be used in a React application:</p><pre>import { useQuery, useMutation, QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br><br>// Create a client<br>const queryClient = new QueryClient();<br><br>// Define a query function<br>const fetchTodos = async () =&gt; {<br>  const response = await fetch(&#39;/api/todos&#39;);<br>  return response.json();<br>};<br><br>// Define a mutation function<br>const addTodo = async (newTodo) =&gt; {<br>  const response = await fetch(&#39;/api/todos&#39;, {<br>    method: &#39;POST&#39;,<br>    body: JSON.stringify(newTodo),<br>  });<br>  return response.json();<br>};<br><br>function Todos() {<br>  // Use the useQuery hook to fetch data<br>  const { data, error, isLoading } = useQuery(&#39;todos&#39;, fetchTodos);<br><br>  // Use the useMutation hook to handle data mutation<br>  const mutation = useMutation(addTodo, {<br>    onSuccess: () =&gt; {<br>      // Invalidate and refetch<br>      queryClient.invalidateQueries(&#39;todos&#39;);<br>    },<br>  });<br><br>  if (isLoading) return &#39;Loading...&#39;;<br>  if (error) return &#39;An error occurred: &#39; + error.message;<br><br>  return (<br>    &lt;div&gt;<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>      &lt;button<br>        onClick={() =&gt; {<br>          mutation.mutate({ title: &#39;New Todo&#39; });<br>        }}<br>      &gt;<br>        Add Todo<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default function App() {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;Todos /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><h3>Conclusion</h3><p>TanStack Query is a versatile and powerful tool for managing server state in React applications. It abstracts away the complexities of data fetching, caching, synchronization, and error handling, allowing developers to focus on building great user experiences. Whether you’re building simple applications or complex, data-intensive applications, TanStack Query provides the tools you need to manage your data effectively.</p><h4><strong>Resources</strong></h4><ol><li>Official documentation : <a href="https://tanstack.com/query/latest">https://tanstack.com/query/latest</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e37b467a82db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your own note application without using Javascript]]></title>
            <link>https://iamrajatsingh.medium.com/create-your-own-note-application-without-using-javascript-1ea3bc3f670c?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ea3bc3f670c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 18:47:23 GMT</pubDate>
            <atom:updated>2025-01-16T18:47:23.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create your own editable app for Notes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O9NbZ3YRqOQjApBZ" /></figure><blockquote>In this blog, we’ll explore how to build a minimalist application that transforms the entire web page into an editable text area.</blockquote><h3>The Core Idea</h3><p>The magic behind this app lies in the HTML contenteditable attribute. By setting this attribute to true on an HTML element, the browser allows users to edit its content directly. There’s no need for JavaScript to enable the editing functionality, making it a lightweight and efficient approach.</p><h3>Building the App</h3><p>Here’s the full code for the app:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Editable DOM&lt;/title&gt;<br>    &lt;style&gt;<br>        body {<br>            margin: 0;<br>            padding: 0;<br>            height: 100vh;<br>            display: flex;<br>            justify-content: center;<br>            align-items: center;<br>            font-family: Arial, sans-serif;<br>        }<br><br>        .editable {<br>            width: 90%;<br>            height: 90%;<br>            border: 1px solid #ccc;<br>            padding: 10px;<br>            overflow: auto;<br>            outline: none;<br>            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);<br>            border-radius: 8px;<br>            background-color: #f9f9f9;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;editable&quot; contenteditable=&quot;true&quot;&gt;<br>        &lt;p&gt;Start editing here...&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>How It Works</h3><ol><li><strong>HTML Structure:<br>- </strong>The div element with the class editable is the primary container where users can write and edit.<br>- The contenteditable=&quot;true&quot; attribute enables editing functionality for this container.</li><li><strong>CSS Styling: <br>- </strong>The .editable class ensures the editing area is visually appealing and user-friendly.<br>- Padding, borders, and a subtle box-shadow create a clean, modern look.</li><li><strong>Default Content:<br>- </strong>The &lt;p&gt;Start editing here...&lt;/p&gt; tag provides a default placeholder for the user.</li></ol><h3>Advantages of This Approach</h3><ul><li><strong>Lightweight:</strong> No JavaScript is needed, so the app loads quickly.</li><li><strong>Flexible:</strong> Users can freely add paragraphs, headings, and other inline elements.</li><li><strong>Cross-Browser Support:</strong> The contenteditable attribute is supported by all major browsers.</li></ul><h3>Conclusion</h3><p>This editable DOM app is a quick and efficient way to enable in-browser text editing. It’s lightweight, easy to implement, and provides a foundation for more advanced features if needed. Try it out and let your creativity flow!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ea3bc3f670c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Paint flashing tool and FPS stats in browser developer tools]]></title>
            <link>https://iamrajatsingh.medium.com/using-paint-flashing-tool-and-fps-stats-in-browser-developer-tools-24cb6590075c?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/24cb6590075c</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 18:42:58 GMT</pubDate>
            <atom:updated>2024-12-26T18:42:58.479Z</atom:updated>
            <content:encoded><![CDATA[<p>As a frontend developer, optimizing performance is key to a smooth user experience. The <strong>Paint Flashing Tool</strong> in browser developer tools helps you see exactly how your app is re-rendering, highlighting areas that may be causing slowdowns. Paired with real-time <strong>FPS stats</strong>, it’s a powerful combo for spotting performance issues. In this blog, we’ll explore how these tools work and how you can use them to fine-tune your app’s rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGEHkmisnvRLkKEZ6AQAcg.png" /><figcaption>Paint flashing option in dev tools</figcaption></figure><h3>1. What Is the Paint Flashing Tool?</h3><p>The Paint Flashing Tool is a feature in browser developer tools that visually highlights areas of a webpage that are being repainted. When enabled, the browser overlays flashing rectangles on elements that are being re-rendered, making it easy to see what parts of the page are affected during user interactions or code execution.</p><p>This tool is particularly helpful for identifying paint operations, which occur when:</p><ul><li>New content is drawn on the screen.</li><li>Style changes require parts of the page to be visually updated.</li><li>Animations or transitions trigger repaints.</li></ul><h3>Why Frontend Developers Should Use Paint Flashing</h3><p>Efficient rendering is critical for web performance, especially in modern web applications with dynamic and interactive elements. The Paint Flashing Tool helps developers:</p><ul><li><strong>Visualize Rendering Behavior: </strong>Easily spot which parts of the page are being repainted during interactions, such as scrolling, resizing, or hovering over elements.</li><li><strong>Detect Inefficient Re-renders: </strong>Identify areas where unnecessary repaints are occurring due to inefficient code or improper state management. By also tracking frames per second (FPS), you can pinpoint which repaints are causing performance drops or stutters.</li><li><strong>Debug Performance Bottlenecks: </strong>Focus on optimizing components or styles that cause frequent or large repaints. Combined with FPS stats, you can evaluate how these repaints impact the smoothness of your application, especially during animations or transitions.</li><li><strong>Optimize Animations and Transitions: </strong>Ensure animations run smoothly by minimizing the areas being repainted during each frame. By monitoring FPS, you can verify that animations are not dropping frames and are performing optimally.How to Enable the Paint Flashing Tool</li></ul><h4>Chrome (or Chromium-based browsers):</h4><ul><li>Open <strong>DevTools</strong> by pressing Ctrl + Shift + I (Windows/Linux) or Cmd + Option + I (Mac).</li><li>Go to the <strong>Rendering</strong> tab. If it’s not visible, open the <strong>Command Menu</strong> (press Ctrl + Shift + P / Cmd + Shift + P) and search for “Rendering”.</li><li>Under the <strong>Rendering</strong> tab, check the box labeled <strong>Paint Flashing</strong>.</li><li>Interact with your page and observe the flashing areas.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tveVzftVmNhxTqKmJ9B9cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i1wKQINF8F3e8IxvGR4v-Q.png" /></figure><h4>Using Paint Flashing to Debug Re-rendering</h4><h4>1. Spotting Unintended Repaints</h4><p>For example, if clicking a button causes unrelated components to repaint, this could indicate:</p><ul><li>Overuse of global state.</li><li>Inefficient DOM structure.</li><li>Excessive use of CSS properties like box-shadow or transform that trigger repaints.</li></ul><h4>2. Improving Animation Performance</h4><p>When working with animations, excessive paint flashing suggests that too many elements are being repainted. Optimizations include:</p><ul><li>Using transform and opacity instead of width, height, or top for animations.</li><li>Leveraging the GPU by specifying will-change properties.</li></ul><h4>3. Identifying Expensive Styles</h4><p>Some CSS properties like filter, clip-path, and blend-mode are expensive to repaint. Paint flashing can help identify where these properties impact performance.</p><h3>2. What Are FPS Stats and How Can They Improve Your Performance?</h3><p>In addition to using the Paint Flashing Tool, another valuable feature in browser developer tools is the ability to view the <strong>frames per second (FPS)</strong> in real time, along with frame rendering stats. This feature provides insight into how well your application is performing, particularly during animations or complex interactions.</p><p><strong>Why FPS Matters:</strong> FPS is an essential metric for understanding how smoothly your application runs. If the FPS drops below 60 (the standard target for smooth animations), it can result in stuttery or laggy performance, making the user experience feel less responsive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*HxWBjp0ZBb-H9xTsf3jvxA.png" /></figure><h3><strong>How to Enable FPS Stats:</strong></h3><p><strong>Chrome (or Chromium-based browsers):</strong></p><ol><li>Open DevTools by pressing <strong>Ctrl + Shift + I</strong> (Windows/Linux) or <strong>Cmd + Option + I</strong> (Mac).</li><li>Open the <strong>Performance</strong> tab.</li><li>Click on the <strong>FPS meter</strong> button in the top right corner of the Performance tab to overlay FPS stats on your page.</li><li>Interact with your page and observe how the FPS changes as elements are repainted or animations are running.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pL4jpOFrpMfl5TcRV2W6oQ.png" /></figure><p><strong>Using FPS Stats for Debugging:</strong> By monitoring FPS, you can:</p><ul><li>Identify performance bottlenecks that cause frame drops.</li><li>Pinpoint specific areas of your application that need optimization.</li><li>Improve the performance of animations, transitions, and general page rendering by reducing reflows and repaints.</li></ul><h3>Best Practices for Efficient Rendering</h3><ul><li><strong>Minimize Layout Thrashing</strong>: Avoid repeatedly querying layout properties like offsetHeight in a loop, as this can trigger unnecessary reflows and repaints, causing performance degradation and FPS drops.</li><li><strong>Use Virtualization</strong>: For large lists or tables, render only visible elements using libraries like react-window or virtual-scroll. This reduces the number of elements being repainted and can help maintain a stable FPS, especially when dealing with long lists or heavy data.</li><li><strong>Debounce State Updates</strong>: Prevent excessive renders by debouncing input events or state updates. This helps to reduce unnecessary reflows and repaints, contributing to more stable FPS during user interactions.</li><li><strong>Profile Rendering Behavior</strong>: Combine Paint Flashing with the Performance tab in DevTools to get a comprehensive view of rendering costs. Monitoring FPS alongside repaints will help you identify performance bottlenecks and areas that need optimization, ensuring smoother interactions and animations.</li><li><strong>Monitor FPS During Animations</strong>: Keep an eye on FPS stats while working on animations or complex interactions. If FPS drops below 60, investigate areas causing excessive reflows or repaints, and optimize them to maintain a smooth user experience.</li></ul><h3><strong>Conclusion</strong></h3><p>The Paint Flashing Tool and FPS stats are simple yet powerful ways to visualize and debug rendering behavior in web applications. By identifying inefficient repaints and monitoring FPS in real time, you can pinpoint performance bottlenecks and optimize your application’s responsiveness. Whether you’re addressing frequent repaints or stuttery animations, these tools guide you toward the root cause of performance issues.</p><p>Happy debugging!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24cb6590075c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing WebSocket Reliability in React: A Fallback Mechanism for Seamless Connectivity]]></title>
            <link>https://iamrajatsingh.medium.com/enhancing-websocket-reliability-in-react-a-fallback-mechanism-for-seamless-connectivity-8b2b79659cc0?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b2b79659cc0</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 20:46:04 GMT</pubDate>
            <atom:updated>2024-11-14T20:46:04.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fcaBmRhDNewq5ry6JN4wQ.png" /></figure><h3>Introduction:</h3><ol><li>In a world driven by real-time data, <strong>WebSockets</strong> play a crucial role in <strong>building interactive web applications</strong>, enabling fast, two-way communication between servers and clients.</li><li>However, <strong>WebSocket</strong> <strong>connections</strong> <strong>can fail</strong> due to various factors, such as network instability, server downtime, or temporary outages.</li><li><strong>To tackle this issue</strong> and ensure continuous data flow, we can implement a <strong>WebSocket fallback mechanism</strong>.</li></ol><p>In this post, we’ll explore how to build a fallback system that switches to a secondary WebSocket connection when the primary one fails — keeping your application resilient and reliable.</p><h4>Why Implement a WebSocket Fallback Mechanism?</h4><p>With WebSockets, when a connection fails, you’re left with data interruptions that can significantly degrade the user experience. A fallback mechanism ensures that:<br>1. <strong>Real-time data flow remains uninterrupted</strong> even if the primary WebSocket fails.<br>2. <strong>User experience is smoother</strong>, as users won’t notice connectivity issues.<br>3. <strong>App reliability increases</strong> through automatic failover and reconnection attempts.</p><h4>How a WebSocket Fallback Mechanism Works</h4><p>The fallback mechanism involves setting up two WebSocket connections:<br>1. <strong>Primary WebSocket</strong>: The main connection that handles data transfer.<br>2. <strong>Secondary WebSocket</strong>: A backup connection activated if the primary WebSocket encounters issues.</p><p>When the primary WebSocket disconnects, the secondary WebSocket automatically takes over. This can be further enhanced by periodically retrying the primary WebSocket to check if it’s back online, allowing the app to switch back to the preferred connection.</p><h3>Building the Fallback Mechanism in React</h3><p>Let’s dive into building a `WebSocketFallback` component in React. This component establishes connections to both primary and secondary WebSocket URLs and includes logic to switch between them as needed.</p><p><strong>Step 1: Setting Up the WebSocket Component</strong></p><p>Start by defining the primary and secondary WebSocket URLs. In this example, the `primaryUrl` is the main WebSocket endpoint, while `secondaryUrl` is the backup endpoint.</p><p>WebSocketFallback.js</p><pre>import React, { useEffect, useState, useRef } from &#39;react&#39;;<br><br>const primaryUrl = &#39;wss://primary.example.com&#39;;<br>const secondaryUrl = &#39;wss://secondary.example.com&#39;;<br><br>const WebSocketFallback = () =&gt; {<br>    const [connectionStatus, setConnectionStatus] = useState(&#39;Connecting to primary...&#39;);<br>    const primarySocket = useRef(null);<br>    const secondarySocket = useRef(null);<br><br>    // Function to handle data received from WebSocket<br>    const handleData = (data) =&gt; {<br>        console.log(&#39;Received data:&#39;, data);<br>        // Handle data here (e.g., update state, trigger events)<br>    };<br><br>    // Function to connect the primary WebSocket<br>    const connectPrimarySocket = () =&gt; {<br>        primarySocket.current = new WebSocket(primaryUrl);<br>        <br>        primarySocket.current.onopen = () =&gt; {<br>            console.log(&#39;Primary WebSocket connected&#39;);<br>            setConnectionStatus(&#39;Connected to primary&#39;);<br>        };<br><br>        primarySocket.current.onmessage = (event) =&gt; {<br>            handleData(event.data);<br>        };<br><br>        primarySocket.current.onclose = () =&gt; {<br>            console.log(&#39;Primary WebSocket closed&#39;);<br>            setConnectionStatus(&#39;Primary connection lost. Connecting to secondary...&#39;);<br>            connectSecondarySocket();<br>        };<br><br>        primarySocket.current.onerror = (error) =&gt; {<br>            console.error(&#39;Primary WebSocket error:&#39;, error);<br>            primarySocket.current.close();<br>        };<br>    };<br><br>    // Function to connect the secondary WebSocket<br>    const connectSecondarySocket = () =&gt; {<br>        if (secondarySocket.current) return;<br><br>        secondarySocket.current = new WebSocket(secondaryUrl);<br><br>        secondarySocket.current.onopen = () =&gt; {<br>            console.log(&#39;Secondary WebSocket connected&#39;);<br>            setConnectionStatus(&#39;Connected to secondary&#39;);<br>        };<br><br>        secondarySocket.current.onmessage = (event) =&gt; {<br>            handleData(event.data);<br>        };<br><br>        secondarySocket.current.onclose = () =&gt; {<br>            console.log(&#39;Secondary WebSocket closed&#39;);<br>            setConnectionStatus(&#39;Reconnecting to primary...&#39;);<br>            setTimeout(connectPrimarySocket, 5000);  // Retry primary connection after a delay<br>        };<br><br>        secondarySocket.current.onerror = (error) =&gt; {<br>            console.error(&#39;Secondary WebSocket error:&#39;, error);<br>            secondarySocket.current.close();<br>        };<br>    };<br><br>    // Effect to initialize the WebSocket connections<br>    useEffect(() =&gt; {<br>        connectPrimarySocket();<br><br>        return () =&gt; {<br>            // Cleanup: Close both sockets on component unmount<br>            primarySocket.current?.close();<br>            secondarySocket.current?.close();<br>        };<br>    }, []);<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h2&gt;WebSocket Connection Status&lt;/h2&gt;<br>            &lt;p&gt;{connectionStatus}&lt;/p&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default WebSocketFallback;</pre><p><strong>Step 2: Adding Retry Logic</strong></p><p>When the primary WebSocket fails, `connectSecondarySocket` is called to initiate the secondary WebSocket connection. In the `onclose` handler for the secondary WebSocket, we set a delay to retry the primary connection, allowing the application to switch back when the primary connection is available.</p><p><strong>Step 3: Handling Data from Both Connections</strong></p><p>The `handleData` function processes data received from either WebSocket, ensuring seamless data handling. This function can be customized to update component state or trigger events in your application.</p><p><strong>Step 4: Component Cleanup</strong></p><p>When the component unmounts, we close both WebSocket connections to avoid memory leaks.</p><h4>Integrating the Component in Your Application</h4><p>Once your `WebSocketFallback` component is ready, integrate it into your application by adding it to your component tree.</p><p>App.js</p><pre>import React from &#39;react&#39;;<br>import WebSocketFallback from &#39;./WebSocketFallback&#39;;<br><br>const App = () =&gt; {<br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;WebSocket Fallback Example&lt;/h1&gt;<br>            &lt;WebSocketFallback /&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default App;</pre><h4>Enhancing Reliability: Additional Best Practices</h4><p>For production use, consider these enhancements:<br>1. <strong>Exponential Backoff for Reconnect</strong>: To avoid overwhelming the server with frequent reconnection attempts, you can implement exponential backoff in retry logic.<br>2. <strong>Heartbeat Mechanism</strong>: Periodically send a ping message to ensure the WebSocket connection is alive.<br>3. <strong>Custom Error Handling</strong>: Show error messages or feedback to users if both connections fail to connect, improving UX.</p><h4>Conclusion</h4><p>Building a WebSocket fallback mechanism in React allows you to create resilient, real-time applications with automatic failover support. By seamlessly switching to a secondary WebSocket connection when the primary fails, you ensure a smooth and uninterrupted user experience. This component can serve as a foundation for further customization, such as adding more WebSocket endpoints, exponential backoff for retries, or heartbeat monitoring.</p><p>With this mechanism in place, your WebSocket connections become more reliable and robust — keeping your application responsive even during unexpected network or server interruptions.</p><p>Please post your queries in comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b2b79659cc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Component Library: Integrating Atomic Design and the Compound Component Pattern]]></title>
            <link>https://iamrajatsingh.medium.com/building-a-component-library-integrating-atomic-design-and-the-compound-component-pattern-5ee9b1a1a8df?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ee9b1a1a8df</guid>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 15:19:31 GMT</pubDate>
            <atom:updated>2024-04-05T15:19:31.593Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In today’s fast-paced development environment, creating scalable and reusable UI components is essential for building maintainable and efficient applications. <br>Two popular methodologies: <strong>Atomic Design and the Compound Component Pattern</strong>, offer powerful approaches to achieving these goals.</blockquote><p>In this blog post, we’ll explore how integrating these methodologies can result in a flexible and robust component library.</p><h3>Atomic Design: Organizing Components Hierarchically</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8_pP1zgl5FPCsByZVhOnQ.png" /></figure><p>Atomic Design, pioneered by <strong>Brad Frost</strong>, is a methodology that breaks down user interfaces into smaller, reusable components organized in a hierarchical manner. At its core, Atomic Design categorizes components into five distinct levels: atoms, molecules, organisms, templates, and pages. Let’s delve into each level:</p><p>- <strong>Atoms</strong>: These are the basic building blocks of a UI, such as buttons, inputs, and icons.<br>- <strong>Molecules</strong>: Molecules are combinations of atoms that form more complex components, such as form fields or buttons with icons.<br>- <strong>Organisms</strong>: Organisms are larger, more complex components composed of groups of molecules and/or atoms, such as headers or cards.<br>- <strong>Templates</strong>: Templates define the layout structure of a page or section, bringing together various organisms.<br>- <strong>Pages</strong>: Pages represent instances of templates populated with actual content, showcasing the final user interface.</p><p>By organising components hierarchically according to Atomic Design principles, we establish a structured foundation for our component library, promoting reusability, scalability, and consistency across projects.</p><h3>Compound Component Pattern: Flexibility through Composition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTBsBNvISrkQ01651m8NPQ.png" /><figcaption>Container Component</figcaption></figure><p>The Compound Component Pattern, commonly used in React and other component-based frameworks, complements Atomic Design by providing a way to create flexible and customizable components. In this pattern, a container component manages the state and behavior of child components, allowing users to compose them in various configurations. Here’s how it works:</p><p>- <strong>Container Component:</strong> This parent component encapsulates the logic and state management of the compound component.<br>- <strong>Child Components:</strong> These individual components form the building blocks of the compound component, each serving a specific role or functionality.<br>- <strong>Props-based Configuration:</strong> Users can customize the behavior and appearance of the compound component by passing props to its child components.<br>- <strong>Composition and Flexibility:</strong> Users can compose the compound component by combining its child components in different ways, adjusting props to achieve desired behaviors.</p><h3>Integrating Atomic Design and Compound Components</h3><p>By integrating Atomic Design principles with the Compound Component Pattern, we create a comprehensive architecture for our component library. Here’s how they work together:</p><p>1. <strong>Atomic Design Structure:</strong> We organize components hierarchically according to Atomic Design principles, establishing a clear structure for our library.<br>2. <strong>Compound Component Flexibility: </strong>Within this structure, we implement compound components using the Compound Component Pattern, offering users flexibility and customization options.<br>3. <strong>Consistency and Reusability:</strong> The combination of Atomic Design and Compound Components promotes consistency, reusability, and maintainability across projects, ensuring a cohesive user experience.</p><pre> ____________________________<br>|         Component          |<br>|         Library            |<br>|____________________________|<br>             |<br>             |<br>   __________|__________<br>  |                     |<br>  |   Container         |<br>  |   Component         |<br>  |_____________________|<br>            |<br>     _______|_______<br>    |               |<br>    |    Atoms      |<br>    |_______________|<br>    |               |<br>    |  Molecules    |<br>    |_______________|<br>    |               |<br>    |  Organisms    |<br>    |_______________|</pre><h3><strong>Conclusion:</strong></h3><p>In today’s dynamic development landscape, a flexible and robust component library is indispensable. By integrating Atomic Design principles with the Compound Component Pattern, we can build a library that offers both structure and flexibility, empowering developers to create scalable and maintainable applications with ease.</p><p>In this blog post, we’ve explored how Atomic Design provides a hierarchical organization for our components, while the Compound Component Pattern offers flexibility through composition. By leveraging these methodologies together, we can create a component library that meets the diverse needs of modern web development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ee9b1a1a8df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Axios: Powerful library]]></title>
            <link>https://iamrajatsingh.medium.com/axios-powerful-library-8fc452af875c?source=rss-cc710fb5c0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc452af875c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[axios-react]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Rajat Singh]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 21:48:24 GMT</pubDate>
            <atom:updated>2023-12-12T18:51:53.255Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxOqnG3MAtGn9D1RyhRXoA.jpeg" /></figure><blockquote>We have <strong>underestimated</strong> <strong>axios</strong> library. I repeat we have <strong>underestimated</strong> it.<br>We must be using it for just making <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequests</a> from the browser or to make <a href="http://nodejs.org/api/http.html">http</a> requests from node.js</blockquote><p>But recently, I got to know about two powerful usages which I would like to share:</p><ol><li><strong>axios-cache-adapter</strong></li></ol><p>It&#39;s a <strong>caching adapter</strong> for axios, which stores request responses in a configurable store to prevent unneeded network requests.</p><p>Check the code below to understand its implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c880668b3da6b55cfe6f11f5dc5401c3/href">https://medium.com/media/c880668b3da6b55cfe6f11f5dc5401c3/href</a></iframe><p><strong>2. axios interceptors</strong></p><p>Basically, this will intercept every request or response that is being sent/received in React application.</p><p>Axios interceptors are the default configurations that are added automatically to every request or response that a user receives.</p><p>It can be utilized in various ways:</p><ul><li>We can create a microservice over this interceptor which takes all the requests triggered from React App and can be used for logging/ audit/ authentication purposes.</li><li>We can log the requests being fired for like 400 Unauthorized or 403 Forbidden error codes to understand the unusual activity happening.</li></ul><p>The idea is simple we can log/ interpret each request which will ultimately increase the App’s security.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2c624d8fa3358192e97065247e0250a/href">https://medium.com/media/e2c624d8fa3358192e97065247e0250a/href</a></iframe><p>This will log each request and will also console log “Posted successfully” on every post 201 response status code.</p><p>As we could see clearly, we can use Axios in various ways from creating a custom adapter to using it to add a security layer in your web app.</p><p>From now on, your perspective towards <strong>Axios</strong> must have changed a bit at least.</p><p>Cheers.<br>Rajat Singh.</p><p>Please like, share and comment.</p><p>More references:</p><ul><li><a href="https://www.tutorialspoint.com/reactjs-axios-interceptors">ReactJS - Axios Interceptors</a></li><li><a href="https://www.pluralsight.com/guides/all-need-to-know-about-axios">Advanced Axios Features | Pluralsight</a></li><li><a href="https://www.npmjs.com/package/axios-cache-adapter">axios-cache-adapter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc452af875c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>