<?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 Shubhankar Misra on Medium]]></title>
        <description><![CDATA[Stories by Shubhankar Misra on Medium]]></description>
        <link>https://medium.com/@shubhankarmisra.bit?source=rss-b450026aa6b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0Fm6yNaJPFxSTkme</url>
            <title>Stories by Shubhankar Misra on Medium</title>
            <link>https://medium.com/@shubhankarmisra.bit?source=rss-b450026aa6b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 02:13:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shubhankarmisra.bit/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[Handling Event Storms During App Freezes]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/handling-event-storms-during-app-freezes-5f9f5e79cf62?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f9f5e79cf62</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 10:31:41 GMT</pubDate>
            <atom:updated>2025-12-30T10:31:41.402Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why disabling a button is not enough, and how to design frontend systems that behave correctly under stress.</em></p><p>Let me start with a situation most frontend engineers have faced.</p><ul><li><em>You have a button.</em></li><li><em>The user clicks it.</em></li><li><em>You disable the button.</em></li><li><em>You fire an API.</em></li></ul><p>Life should be good… right?</p><p>Now imagine this:</p><ul><li>The app freezes for a second</li><li>The user taps the button 5–6 times</li><li>The app unfreezes</li><li><strong>Boom</strong> — 6 API calls go out</li></ul><p>And now you’re dealing with refunds, angry clients, and awkward explanations.</p><p>Let’s talk about <strong>why this happens</strong> and how to design around it.</p><h3>The Hidden Enemy: App Freeze</h3><p>In React Native (and similar frameworks), there’s an important detail many people miss:</p><ul><li>Touches are captured by the <strong>native layer</strong></li><li>Your onPress runs on the <strong>JS thread</strong></li></ul><p>When the JS thread is blocked:</p><ul><li>The UI doesn’t update</li><li>The button doesn’t visually disable</li><li><strong>Taps are still getting registered</strong></li></ul><p>Those taps don’t disappear.<br>They just <strong>wait in a queue</strong>.</p><p>As soon as JS wakes up, every queued onPress runs one after another.</p><p>That’s how one click becomes six API calls.</p><h3>Why “Disable Button” Fails</h3><p>Disabling a button is a <strong>UI change</strong>.<br>UI changes need JS to run.<br>If JS is frozen, the button is <em>not really disabled yet</em>.</p><p>So this logic breaks:</p><blockquote><em>“I disabled the button, so the user can’t click it.”</em></blockquote><p>They already did.<br>The app just hasn’t processed it yet.</p><h3>The Key Insight</h3><p><strong>UI state is not a lock.</strong></p><p>If something must happen only once, you need a <strong>real execution guard</strong>, not just a visual one.</p><p>Think of it like backend APIs:<br>You don’t trust the client.<br>You enforce rules at the entry point.</p><p>Same idea here.</p><h3>The Simple Fix That Actually Works</h3><p>Use an in-memory lock with useRef.</p><pre>const inFlightRef = useRef(false);</pre><pre>const onPress = () =&gt; {<br>  if (inFlightRef.current) return;<br>  inFlightRef.current = true;</pre><pre>  doApiCall().finally(() =&gt; {<br>    inFlightRef.current = false;<br>  });<br>};</pre><p>Why this works:</p><ul><li>useRef updates immediately</li><li>No re-render needed</li><li>Works even after a JS freeze</li><li>Queued clicks get ignored</li></ul><p>Even if 5 clicks were queued:</p><ul><li>First one sets the flag</li><li>Rest exit early</li><li>Only one API call happen</li></ul><h3>“What If the Component Re-renders?”</h3><p>Short answer: <strong>nothing breaks</strong>.</p><ul><li>useRef does NOT reset on re-render</li><li>It only resets on unmount</li><li>Perfect for tracking “action in progress”</li></ul><p>This is exactly why refs exist.</p><h3>UX Still Matters (But It’s Not Enough)</h3><p>You should still:</p><ul><li>Disable the button</li><li>Show a loader</li><li>Give feedback</li></ul><p>But think of that as <strong>polish</strong>, not protection.</p><p>Protection comes from the execution guard.</p><h3>How to Test This Properly</h3><p>Want to see this bug for real?</p><p>Block the JS thread manually:</p><pre>const blockJS = (ms) =&gt; {<br>  const start = Date.now();<br>  while (Date.now() - start &lt; ms) {}<br>};</pre><p>Call it before your API.</p><p>Then:</p><ul><li>Tap the button multiple times</li><li>Let JS unfreeze</li></ul><p>If only one API call happens — your design is solid.</p><h3>One Final Lesson</h3><p>Frontend apps are not just UI anymore.</p><p>They deal with:</p><ul><li>Race conditions</li><li>Queued events</li><li>Partial failures</li><li>Real money</li></ul><p>If your logic only works when the app is “smooth and fast”, it’s fragile.</p><p>Design for:</p><ul><li>Slow devices</li><li>Frozen threads</li><li>Impatient users</li></ul><p>Your future self (and your support team) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f9f5e79cf62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GEO > SEO: Why AI Doesn’t Care About Your Keywords Anymore]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/geo-seo-why-ai-doesnt-care-about-your-keywords-anymore-d1419176d962?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1419176d962</guid>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 06:07:33 GMT</pubDate>
            <atom:updated>2025-12-11T06:07:33.532Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s be real:<br> <strong>Google is no longer the front door of the internet.</strong><br> ChatGPT, Perplexity, and every other AI assistant has quietly taken that position.</p><p>People don’t <em>search</em> now.<br> They <em>ask</em>.<br> And AI answers — instantly, confidently, and without ever visiting your website.</p><p>That’s why <strong>SEO is losing power</strong>, and <strong>GEO (Generative Experience Optimization)</strong> is becoming the new survival strategy.</p><h3>What is GEO?</h3><p><strong>GEO = Making your product understandable to AI, not just visible to Google.</strong></p><p>SEO is about keywords and crawling.<br>GEO is about <strong>meaning and reasoning</strong>.</p><p>If AI can’t understand what your app does, your app simply doesn’t exist in its world.</p><h3>Why SEO Isn’t Enough Anymore</h3><p>AI does not:</p><ul><li>scroll</li><li>click</li><li>skim your homepage</li><li>admire your graphics</li></ul><p>It <strong>summarizes</strong>, <strong>reasons</strong>, and <strong>recommends</strong>.</p><p>A single user prompt like:<em>“Which app is best for comparing PG, rent, and resale properties?”</em></p><p>is answered entirely inside an AI model.</p><p>If your product isn’t part of the model’s internal “knowledge map”, you will never be recommended — no matter how good your SEO is.</p><h3>How to Improve GEO?</h3><h3>1. Structure &gt; Keywords</h3><p>AI understands <strong>schemas</strong>, <strong>APIs</strong>, <strong>state machines</strong>, <strong>clean code</strong>, and <strong>structured docs</strong>.<br> Give it machine-friendly knowledge, not marketing fluff.</p><h3>2. Make Your UI AI-Readable</h3><p>As an Engineer, here’s my rule:</p><p><em>If an AI model can’t explain your component, it’s too complex.</em></p><p>Small components.<br>Clear responsibilities.<br>Predictable naming.</p><p>This dramatically improves GEO.</p><h3>3. Docs for Models, Not Managers</h3><p>Write documentation in a way AI loves:</p><ul><li>short sections</li><li>bullet rules</li><li>examples</li><li>no story writing</li></ul><p>Think “training data”, not “wiki”.</p><h3>4. Publish AI Actions</h3><p>Don’t force AI to guess how your app works.</p><p>Expose:</p><ul><li>function calls</li><li>input/output formats</li><li>feature capabilities</li></ul><p>This is how AI agents integrate with your product.</p><h3>5. Test Your GEO Like You Test Your Code</h3><p>Ask LLMs:</p><ul><li>“Explain feature X.”</li><li>“Generate how a user completes flow Y.”</li><li>“Fix this bug.”</li></ul><p>If the answer is wrong → your GEO is weak.</p><h3>My Approach</h3><p>Here’s how I tackle GEO in real projects:</p><ul><li>I <strong>design for AI interpretability first</strong></li><li>I refactor anything AI can’t reason about</li><li>I treat documentation as <strong>structured input</strong>, not text</li><li>I ensure every feature can be explained in a few bullet points</li><li>I use AI to validate component clarity and flow logic</li></ul><p>This “AI-first engineering” mindset beats legacy SEO playbooks every single time.</p><h3>Final Take</h3><p>AI isn’t the future — it’s the interface people are already using.</p><p>SEO helped you get discovered by search engines.<br><strong>GEO helps you get discovered by AI agents.</strong></p><p>If your product isn’t optimized for AI understanding, it will slowly disappear from the recommendation layer of the internet.</p><p>The shift is already happening.</p><p><strong>The ones who adapt to GEO will be the ones who stay relevant.</strong></p><p>NOTE: Next up will be something more on AEO.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1419176d962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own useContextSelector — No Extra Package Needed]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/build-your-own-usecontextselector-no-extra-package-needed-0395406c78ba?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0395406c78ba</guid>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 13:03:29 GMT</pubDate>
            <atom:updated>2025-11-11T13:03:29.103Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Your Own useContextSelector — No Extra Package Needed</h3><p>React’s Context API is powerful, but it often causes <strong>unnecessary re-renders</strong>.<br> Even if your component only needs part of the context, it still re-renders whenever <em>anything</em> in that context changes.</p><p>Let’s fix that — with a <strong>tiny custom hook</strong> that gives you selector-based context updates (like use-context-selector) without adding another dependency.</p><h3>🎯 The Goal</h3><p>We want to consume only a <em>slice</em> of context — and re-render only when that slice changes.</p><h3>🪄 The Hook</h3><pre>import { useContext, useRef, useEffect, useState } from &quot;react&quot;;</pre><pre>const useContextSelector = (Context, selector, compareFunction) =&gt; {<br>  const contextValue = useContext(Context);<br>  if (contextValue == null)<br>    throw new Error(&quot;useContextSelector must be used within a Provider&quot;);</pre><pre>  const selectedValue = selector(contextValue);<br>  const [, forceRender] = useState({});<br>  const prevRef = useRef(selectedValue);<br>  const isEqual = (a, b) =&gt; Object.is(a, b);</pre><pre>  useEffect(() =&gt; {<br>    const compare = compareFunction || isEqual;<br>    if (!compare(prevRef.current, selectedValue)) {<br>      prevRef.current = selectedValue;<br>      forceRender({});<br>    }<br>  }, [selectedValue]);</pre><pre>  return selectedValue;<br>};</pre><pre>export default useContextSelector;</pre><h3>⚙️ Usage</h3><pre>const theme = useContextSelector(ThemeContext, (ctx) =&gt; ctx.theme);<br>const fontSize = useContextSelector(ThemeContext, (ctx) =&gt; ctx.fontSize);</pre><p>Now, changing theme won’t re-render components using fontSize, and vice-versa.</p><p>Need custom comparison?</p><pre>const image = useContextSelector(<br>  ImageContext,<br>  (ctx) =&gt; ctx.data.image,<br>  (prev, next) =&gt; prev.url === next.url<br>);</pre><h3>💡 Why Not Use the use-context-selector Package?</h3><p>The npm package is great — but this version:</p><ul><li>🚫 Needs <strong>no dependency</strong></li><li>⚙️ Is <strong>simpler and transparent</strong></li><li>🧩 Lets you <strong>tweak behavior</strong> easily</li><li>📦 Keeps your bundle smaller</li></ul><p>Unless you’re building a massive app where micro-optimizations matter, this minimal hook does the job beautifully.</p><h3>🏁 Takeaway</h3><p>React Context causes full re-renders by default.<br> This small hook gives you fine-grained control — <strong>only re-rendering when your selected value actually changes.</strong></p><p>Lightweight. Customizable. Dependency-free.</p><p>A perfect utility to drop into your React toolkit 💪</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0395406c78ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Overusing Hooks: Finding the Right Abstraction in React]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/stop-overusing-hooks-finding-the-right-abstraction-in-react-f770ab5436c1?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f770ab5436c1</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks-in-react]]></category>
            <category><![CDATA[hooks]]></category>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Mon, 19 May 2025 07:49:12 GMT</pubDate>
            <atom:updated>2025-05-19T07:49:12.812Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>React Hooks are powerful, but with great power comes the tendency to overuse them. Let’s explore when </em><strong><em>Hooks</em></strong><em>, </em><strong><em>Render Props</em></strong><em>, and </em><strong><em>HOCs</em></strong><em> each shine — and why a balanced approach is key.</em></blockquote><h3>The Hook Addiction</h3><p>When React introduced Hooks in v16.8, it was a game-changer. It eliminated the need for class components and made code more functional, declarative, and readable. But as the ecosystem evolved, so did the habit of over-engineering with Hooks — turning even simple logic into overly abstracted custom hooks.</p><p>Sound familiar?</p><ul><li>You see dozens of tiny hooks sprinkled across files.</li><li>Logic that could live in a helper function is unnecessarily stateful.</li><li>You’re fighting the rules-of-hooks linter just to get things working.</li></ul><p>While Hooks are great, they aren’t <em>always</em> the best tool for every abstraction.</p><h3>Let’s Break It Down: Hooks vs HOC vs Render Props</h3><p>Before we go further, let’s get a clear understanding of the three patterns.</p><h3>1. Hooks</h3><p>Hooks are functions that let you “hook into” React state and lifecycle features from function components.</p><p>Example:</p><pre>function useWindowSize() {<br>  const [size, setSize] = useState(window.innerWidth);<br>  useEffect(() =&gt; {<br>    const handleResize = () =&gt; setSize(window.innerWidth);<br>    window.addEventListener(&#39;resize&#39;, handleResize);<br>    return () =&gt; window.removeEventListener(&#39;resize&#39;, handleResize);<br>  }, []);<br>  return size;<br>}</pre><p>✅ <strong>Good for:</strong> Reusing stateful logic in a functional, readable way.</p><p>🚫 <strong>Bad when:</strong> Used for everything — even things that don’t require state or lifecycle.</p><h3>2. Higher-Order Components (HOC)</h3><p>HOCs are functions that take a component and return a new component with enhanced behavior.</p><pre>function withAuth(Component) {<br>  return function AuthWrapper(props) {<br>    const isLoggedIn = useAuthCheck();<br>    return isLoggedIn ? &lt;Component {...props} /&gt; : &lt;Redirect to=&quot;/login&quot; /&gt;;<br>  };<br>}</pre><p>✅ <strong>Good for:</strong> Code reuse, especially in Server-Side Rendering (SSR) or when you want static optimization.</p><p>🚫 <strong>Bad when:</strong> Over-nesting leads to “wrapper hell” or makes debugging painful.</p><h3>3. Render Props</h3><p>Render Props use a prop whose value is a function that returns JSX, allowing for dynamic rendering logic.</p><pre>function MouseTracker({ render }) {<br>  const [position, setPosition] = useState({ x: 0, y: 0 });<br>  useEffect(() =&gt; {<br>    const handleMouseMove = e =&gt; setPosition({ x: e.clientX, y: e.clientY });<br>    window.addEventListener(&#39;mousemove&#39;, handleMouseMove);<br>    return () =&gt; window.removeEventListener(&#39;mousemove&#39;, handleMouseMove);<br>  }, []);<br>  return render(position);<br>}</pre><p>✅ <strong>Good for:</strong> Dynamic logic sharing without HOC wrapping.</p><p>🚫 <strong>Bad when:</strong> Overused, leading to unreadable “pyramid of doom.”</p><h3>Why You Shouldn’t Overdo Any of Them</h3><p>Every pattern in React was created to solve a specific problem. Overusing any of them leads to:</p><ul><li><strong>Poor readability</strong>: Too many hooks make logic hard to follow.</li><li><strong>Debugging nightmares</strong>: Nesting HOCs or render props makes stack traces confusing.</li><li><strong>Performance issues</strong>: Unoptimized custom hooks can cause unnecessary re-renders.</li><li><strong>Tight coupling</strong>: Over-abstraction leads to components being harder to reuse or test.</li></ul><blockquote><em>Just because you </em>can<em> make everything a hook, doesn’t mean you </em>should<em>.</em></blockquote><h3>So When Should You Use What?</h3><p>Scenario Recommended Pattern Sharing side-effect logic Custom Hook Injecting static behavior HOC Sharing state between unrelated comps Render Prop or Context Need SSR optimization HOC Simple utility function Regular JS function</p><h3>Why HOCs Work Better for SSR</h3><p>In Server-Side Rendering, you want to minimize dynamic behavior and maximize pre-rendered output.</p><p>Here’s why <strong>HOCs are SSR-friendly</strong>:</p><ul><li>HOCs wrap your component before rendering — meaning logic like data fetching, redirects, or static props can be evaluated on the server.</li><li>Hooks require components to render to invoke logic, which only happens on the client, making them less ideal for SSR-driven apps like Next.js unless used in getServerSideProps.</li></ul><p><strong>Example:</strong></p><pre>// pages/dashboard.js<br>export default withAuth(DashboardPage); // SSR-safe guard</pre><pre>// vs</pre><pre>function DashboardPage() {<br>  const auth = useAuth(); // Too late for SSR redirect<br>}</pre><h3>Final Thoughts</h3><p>React gives us several patterns to build composable, reusable components. But like any toolbox, knowing <strong>when and how to use each tool</strong> is what makes a developer great.</p><p>So next time you reach for a hook:</p><p>✅ Ask: <em>Does this really need to be a hook?</em></p><p>✅ Consider: <em>Could an HOC or Render Prop serve better here?</em></p><p>✅ Remember: <em>Abstractions should clarify — not complicate.</em></p><ul><li><strong>Hooks</strong> are great for side-effect logic in components, but don’t hook everything.</li><li><strong>Render Props</strong> are useful for flexibility but reduce readability if overused.</li><li><strong>HOCs</strong> are a solid choice for SSR and code reuse — don’t forget their value in a hook-obsessed world.</li></ul><p>If you liked this article, give it a 👏 and share it with your React friends who might be stuck in hook hell. Let’s build smarter, not just trendier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f770ab5436c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Why You Should Be a Platform-Agnostic Frontend Developer (Not a Framework Technician)]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/why-you-should-be-a-platform-agnostic-frontend-developer-not-a-framework-technician-e24f53ad4e88?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e24f53ad4e88</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 10:12:34 GMT</pubDate>
            <atom:updated>2025-04-29T10:12:34.153Z</atom:updated>
            <content:encoded><![CDATA[<p>Frontend development has exploded in complexity. We’re no longer just crafting static pages — we’re building full-blown applications across web, mobile, and desktop using an ever-changing sea of frameworks: React, Vue, Angular, Svelte, React Native, Flutter… and the list keeps growing.</p><p>In this fast-paced ecosystem, being a <strong>framework technician</strong> — someone who only knows one tool deeply — is no longer enough.</p><p>It’s time to adopt a <strong>platform-agnostic mindset</strong> — where you focus on principles, patterns, and architecture, not just tools. Here’s why that shift is crucial now more than ever.</p><h3>🧠 1. Frameworks Change — Fundamentals Don’t</h3><p>Frameworks come and go. What doesn’t?</p><ul><li>The DOM</li><li>Layout systems (Flexbox, Grid)</li><li>Rendering lifecycles</li><li>Accessibility (a11y)</li><li>Performance optimization</li><li>State and data flow</li><li>Event handling</li></ul><p>If you deeply understand these fundamentals, you can pick up <em>any</em> framework fast. Frameworks are just abstractions over the same core problems — layout, interaction, and reactivity.</p><p>Stop chasing the syntax. Start mastering the system.</p><h3>🧩 2. You Solve Problems Beyond Framework Boundaries</h3><p>Framework-specific devs often think in patterns dictated by their tool. Platform-agnostic devs ask bigger questions:</p><ul><li>What’s the best solution <em>regardless</em> of framework?</li><li>Is this concern even frontend-related?</li><li>Should this logic live in middleware, or the UI?</li></ul><p>This mindset leads to:</p><ul><li>Cleaner code architecture</li><li>Smarter abstractions</li><li>Reduced coupling between layers</li><li>Interfaces that scale across platforms</li></ul><p>Frameworks should be <em>tools</em>, not <em>limits</em>.</p><h3>🔁 3. You’re Ready for a Multi-Framework Reality</h3><p>Real-world apps aren’t built with a single tech. You might see:</p><ul><li>A React dashboard</li><li>A marketing site in Astro or Nuxt</li><li>A mobile app in Flutter</li><li>A native wrapper using Electron or Tauri</li></ul><p>Being platform-agnostic means you:</p><ul><li>Recognize patterns across stacks</li><li>Can switch tools without anxiety</li><li>Focus on <em>concepts</em>, not <em>syntax</em></li></ul><p>It’s not about knowing every framework — it’s about understanding <em>how they think</em>.</p><h3>🤝 4. You Collaborate Better with Everyone</h3><p>Great frontend developers act as a bridge between teams. Platform-agnostic devs can:</p><ul><li><strong>Speak design</strong>: Understand UX flows, responsive behavior, accessibility</li><li><strong>Speak backend</strong>: Know what APIs need for optimal UI performance</li><li><strong>Speak product</strong>: Understand trade-offs and deliver value-driven solutions</li></ul><p>When you’re not boxed into one way of thinking, you’re free to speak everyone’s language.</p><h3>📱 5. Cross-Platform Development Is the Norm</h3><p>We now build apps that span web, mobile, and desktop. Examples:</p><ul><li><strong>React Native</strong> for mobile</li><li><strong>Flutter</strong> for cross-platform UI</li><li><strong>Electron</strong> or <strong>Tauri</strong> for desktop</li><li><strong>Expo</strong>, <strong>NativeBase</strong>, and <strong>MUI</strong> for shared components</li></ul><p>Platform-agnostic devs think in <strong>interfaces</strong>, not platforms. They design for <em>humans</em>, not <em>browsers</em>. This perspective is essential for building unified, consistent experiences across devices.</p><h3>🤖 6. Frontend Skills Future-Proof You in the Age of AI</h3><p>AI is transforming how we build — but it still needs <em>someone</em> to craft the human-facing experience.</p><p>Here’s why platform-agnostic frontend devs thrive in an AI world:</p><ul><li><strong>AI needs interfaces</strong>: Someone has to turn prompts and predictions into useful, elegant UIs.</li><li><strong>Prototyping is key</strong>: AI tools demand fast iteration. Frontend devs build fast, testable experiences.</li><li><strong>You bring context</strong>: AI doesn’t understand the nuance of UX, branding, or user flow — you do.</li><li><strong>New AI platforms need frontend glue</strong>: Whether you’re integrating ChatGPT, building agents, or creating dashboards — frontend is where AI meets users.</li></ul><p>You don’t compete with AI. You <em>amplify</em> it.</p><h3>🧭 7. How to Become Platform-Agnostic</h3><p>It’s not a course. It’s a shift in thinking.</p><p>Start here:</p><p>✅ <strong>Focus on the “why”</strong> — Learn concepts like state, reactivity, and lifecycle in <em>multiple</em> frameworks<br> ✅ <strong>Study the web deeply</strong> — Understand native browser APIs, layout systems, accessibility, the rendering pipeline<br> ✅ <strong>Build across platforms</strong> — Try mobile (React Native), desktop (Electron), and static site generators (Astro)<br> ✅ <strong>Compare patterns</strong> — See how different frameworks handle the same problem<br> ✅ <strong>Think in primitives</strong> — Components, composition, user input, async handling — these are universal</p><p>Don’t be a framework expert. Be a <strong>UI problem-solver</strong>.</p><h3>🧠 Final Thought: Be Known for How You Think, Not What You Use</h3><p>Being a “React dev” might get you started. But being a <strong>frontend architect who can think across platforms and tools</strong> — that’s future-proof.</p><p>Tools will evolve. AI will assist more. But the need to design and build thoughtful, intuitive, consistent interfaces across the digital world?</p><p>That’s not going anywhere.</p><p>And the people who can do that — regardless of framework, screen size, or AI model — will lead the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e24f53ad4e88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Normalization: Why It Matters and How to Do It Right]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/redux-normalization-why-it-matters-and-how-to-do-it-right-ade7191815aa?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade7191815aa</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 06:51:30 GMT</pubDate>
            <atom:updated>2025-03-18T06:51:30.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*EHGb9qOheLrrt6B4txvZ3Q.png" /></figure><h3>Introduction</h3><p>Redux is a powerful state management tool, but as applications grow, so does the complexity of managing data. One of the biggest challenges developers face is handling deeply nested state structures, which can lead to inefficient updates, increased rendering, and unnecessary complexity.</p><p>This is where <strong>Redux normalization</strong> comes in. By structuring our state efficiently, we can improve performance, scalability, and maintainability. In this article, we’ll explore why normalization is necessary, what happens if it’s ignored, and best practices for structuring your Redux state correctly.</p><h3>Why is Normalization Needed in Redux?</h3><p>When dealing with relational data (like users, posts, comments, etc.), it’s common to store data in a nested format. However, this approach has several drawbacks:</p><ol><li><strong>Inefficient Updates</strong>: Updating deeply nested data requires multiple state mutations, leading to complex reducers.</li><li><strong>Performance Bottlenecks</strong>: Since Redux follows immutability principles, deeply nested structures cause unnecessary re-renders.</li><li><strong>Difficult State Management</strong>: Retrieving and updating specific entities can become cumbersome.</li><li><strong>Storing Data in an Array is Inefficient</strong>: Arrays require iterating over all elements for lookups, updates, or deletions, making them inefficient for large datasets. A normalized structure using an object with IDs as keys provides O(1) lookup time instead of O(n).</li></ol><p>To solve these issues, Redux normalization structures state in a way that mimics a relational database, where each entity is stored separately and referenced by IDs.</p><h3>The Impact of Not Normalizing State</h3><p>Let’s look at an example of a <strong>non-normalized</strong> state:</p><pre>const state = {<br>  posts: [<br>    {<br>      id: 1,<br>      title: &quot;Redux Normalization&quot;,<br>      author: {<br>        id: 101,<br>        name: &quot;Alice&quot;<br>      }<br>    },<br>    {<br>      id: 2,<br>      title: &quot;Why Normalize State?&quot;,<br>      author: {<br>        id: 102,<br>        name: &quot;Bob&quot;<br>      }<br>    }<br>  ]<br>};</pre><h3>Problems with this Approach:</h3><ul><li>If we update Alice&#39;s name, we need to find and update every post where she appears.</li><li>If an author appears multiple times, we store redundant data.</li><li>Fetching related data (e.g., getting a post’s author) requires iterating through nested structures.</li><li><strong>Inefficient Lookups</strong>: Since posts are stored in an array, searching for a specific post or author requires iterating over the entire list (O(n) complexity), whereas an object-based approach allows direct access (O(1) complexity).</li></ul><h3>The Benefits of Normalization</h3><p>A <strong>normalized</strong> state separates entities and references them by their IDs:</p><pre>const state = {<br>  posts: {<br>    byId: {<br>      1: { id: 1, title: &quot;Redux Normalization&quot;, author: 101 },<br>      2: { id: 2, title: &quot;Why Normalize State?&quot;, author: 102 }<br>    },<br>    allIds: [1, 2]<br>  },<br>  users: {<br>    byId: {<br>      101: { id: 101, name: &quot;Alice&quot; },<br>      102: { id: 102, name: &quot;Bob&quot; }<br>    },<br>    allIds: [101, 102]<br>  }<br>};</pre><h3>Advantages of this Approach:</h3><ol><li><strong>Efficient Updates</strong>: Changing Alice’s name now requires only a single update in users.byId.</li><li><strong>Reduced Redundancy</strong>: No duplicate copies of user data across posts.</li><li><strong>Faster Lookups</strong>: Accessing related data is quick using IDs.</li><li><strong>Scalability</strong>: Works well as the app grows.</li><li><strong>Optimized Performance</strong>: Avoids O(n) lookups that arrays introduce, ensuring O(1) direct access to entities.</li></ol><h3>🛠️ How to Normalize Redux State</h3><h3>1️⃣ Use normalizr for Data Transformation</h3><p>The <a href="https://github.com/paularmstrong/normalizr">normalizr</a> library automatically converts deeply nested data into a normalized structure.</p><h4>Example:</h4><pre>import { normalize, schema } from &quot;normalizr&quot;;</pre><pre>const user = new schema.Entity(&quot;users&quot;);<br>const post = new schema.Entity(&quot;posts&quot;, { author: user });</pre><pre>const data = {<br>  id: 1,<br>  title: &quot;Redux Guide&quot;,<br>  author: { id: 2, name: &quot;Alice&quot; }<br>};</pre><pre>const normalizedData = normalize(data, post);<br>console.log(normalizedData);</pre><p>This converts deeply nested structures into a flat entity-based format.</p><h3>2️⃣ Use Slice Reducers for Each Entity</h3><p>Instead of a single reducer handling everything, split state management by entity.</p><h4>Example:</h4><pre>const usersReducer = (state = {}, action) =&gt; {<br>  switch (action.type) {<br>    case &quot;ADD_USERS&quot;:<br>      return { ...state, ...action.payload };<br>    default:<br>      return state;<br>  }<br>};</pre><h3>3️⃣ Use Selectors for Data Access</h3><p>Since data is now stored separately, we need selectors to retrieve related entities.</p><h4>Example:</h4><pre>const getUserById = (state, id) =&gt; state.users.byId[id];</pre><pre>const getPostWithAuthor = (state, postId) =&gt; {<br>  const post = state.posts.byId[postId];<br>  return { ...post, author: getUserById(state, post.author) };<br>};</pre><h3>4️⃣ Use createEntityAdapter (Redux Toolkit)</h3><p>If using <strong>Redux Toolkit</strong>, createEntityAdapter makes normalization even easier.</p><h4>Example:</h4><pre>import { createSlice, createEntityAdapter } from &quot;@reduxjs/toolkit&quot;;</pre><pre>const usersAdapter = createEntityAdapter();<br>const usersSlice = createSlice({<br>  name: &quot;users&quot;,<br>  initialState: usersAdapter.getInitialState(),<br>  reducers: {<br>    addUser: usersAdapter.addOne,<br>    updateUser: usersAdapter.updateOne,<br>    removeUser: usersAdapter.removeOne,<br>  }<br>});</pre><h3>🎯 Conclusion</h3><p>Redux normalization is a <strong>must</strong> for scalable applications. Without it, managing deeply nested state structures becomes cumbersome and inefficient. By following best practices — such as using normalizr, structuring reducers per entity, and leveraging selectors—you can create a <strong>highly optimized Redux store</strong> that is easy to maintain and scale.</p><p>By embracing normalization, your Redux state will remain <strong>clean, efficient, and manageable</strong> as your application grows.</p><p>🚀 Happy coding! Do you use normalization in your Redux applications? Let me know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade7191815aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Streaming in React with renderToPipeableStream]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/implementing-streaming-in-react-with-rendertopipeablestream-550864bee044?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/550864bee044</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 06:13:39 GMT</pubDate>
            <atom:updated>2025-03-17T06:13:39.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*il9OcmDsPM3v5JP05fpYFA.png" /></figure><p>Server-side rendering (SSR) with streaming enhances performance by allowing the browser to start rendering content before the entire page is fully loaded. This article explores how to implement SSR streaming in a React application using `renderToPipeableStream` from the React 19 release.</p><h3><strong>Setting Up Streaming in React</strong></h3><blockquote>Step 1: Create the Server-Side Controller</blockquote><p>We define a controller function that handles streaming:</p><pre>import React from &#39;react&#39;;<br>import { renderToPipeableStream } from &#39;react-dom/server&#39;;<br><br>import HTML from &#39;../components/HTML&#39;;<br>import App from &#39;../components/App&#39;;<br><br>import * as serverActions from &#39;../store/actions&#39;;<br><br>export const handleStreaming = ({ req, res, next, pageType = &#39;main&#39;, applyHeaders }) =&gt; {<br>  const { assets, criticalCss } = req;<br>  const { isMobile } = req.useragent;<br>  const store = configureStore({ pageType, isMobile });<br>  const Component = getComponent({ pageType, isMobile });<br><br>  const commonParams = { applyHeaders, isSSR: false };<br>  const dataPromises = {<br>    plans: store.dispatch(serverActions.getPlans(commonParams)),<br>    testimonials: store.dispatch(serverActions.getTestimonials(commonParams)),<br>    faqs: store.dispatch(serverActions.getFaqs(commonParams)),<br>    budgetConfig: store.dispatch(serverActions.getBudgetConfig(commonParams)),<br>  };<br>  <br>  const initialState = store.getState();<br>  const criticalStyles = criticalCss[getCriticalCss(pageType, initialState)];<br><br>  const htmlProps = {<br>    ...dataPromises,<br>    criticalStyles,<br>    initialState: JSON.stringify(initialState),<br>    isMobile,<br>  };<br><br>  const stream = renderToPipeableStream(<br>    &lt;HTML {...htmlProps}&gt;<br>      &lt;App store={store}&gt;&lt;Component data={dataPromises} /&gt;&lt;/App&gt;<br>    &lt;/HTML&gt;,<br>    {<br>      onShellReady: () =&gt; {<br>        res.setHeader(&#39;Cache-Control&#39;, &#39;no-store&#39;);<br>        res.setHeader(&#39;Content-Type&#39;, &#39;text/html; charset=utf-8&#39;);<br>        setHeaders(applyHeaders, res);<br>        stream.pipe(res);<br>        console.log(&#39;Shell sent to client&#39;);<br>      },<br>      onError: error =&gt; {<br>        console.error(&#39;Streaming error:&#39;, error);<br>        stream.abort();<br>      },<br>      onShellError: error =&gt; {<br>        console.error(&#39;Shell rendering error:&#39;, error);<br>        stream.abort();<br>      },<br>    },<br>  );<br>};</pre><blockquote>Step 2: Create the Server-Side HTML Component</blockquote><p>The `HTML` component structures the server-rendered HTML and injects scripts to hydrate the client.</p><pre>import React, { Suspense, use } from &#39;react&#39;;<br><br>function ScriptComponent({ dataPromise, globalFunction }) {<br>  const data = use(dataPromise);<br>  return (<br>    &lt;script<br>      dangerouslySetInnerHTML={{<br>        __html: `console.log(&#39;${globalFunction} initialized&#39;); window.${globalFunction}(${JSON.stringify(data)});`,<br>      }}<br>    /&gt;<br>  );<br>}<br><br>const HTML = ({ criticalStyles, children, plans, testimonials, faqs, budgetConfig, processEnv, initialState }) =&gt; (<br>  &lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>      &lt;title&gt;Streaming with React&lt;/title&gt;<br>      &lt;style id=&quot;critical_css&quot; dangerouslySetInnerHTML={{ __html: criticalStyles }}&gt;&lt;/style&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>      &lt;div id=&#39;app&#39;&gt;{children}&lt;/div&gt;<br>      &lt;script dangerouslySetInnerHTML={{ __html: `window.process = { env: ${processEnv} }; window.__initialData__ = ${initialState};` }} /&gt;<br>      &lt;Suspense fallback={&lt;script&gt;&lt;/script&gt;}&gt;<br>        &lt;ScriptComponent dataPromise={testimonials} globalFunction=&quot;setTestimonials&quot; /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;Suspense fallback={&lt;script&gt;&lt;/script&gt;}&gt;<br>        &lt;ScriptComponent dataPromise={faqs} globalFunction=&quot;setFaqs&quot; /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;Suspense fallback={&lt;script&gt;&lt;/script&gt;}&gt;<br>        &lt;ScriptComponent dataPromise={plans} globalFunction=&quot;setPlans&quot; /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;Suspense fallback={&lt;script&gt;&lt;/script&gt;}&gt;<br>        &lt;ScriptComponent dataPromise={budgetConfig} globalFunction=&quot;setBudgetConfig&quot; /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/body&gt;<br>  &lt;/html&gt;<br>);<br><br>export default HTML;</pre><blockquote>How It Works</blockquote><p>1. The server fetches initial data and prepares a Redux store.</p><p>2. `renderToPipeableStream` streams the response incrementally, sending the shell first.</p><p>3. React’s `use` hook ensures promises resolve before hydrating the UI.</p><p>4. The client progressively hydrates the page as data streams in.</p><h3><strong>Hydration on the Client Side</strong></h3><p>Once the streamed HTML reaches the client, hydration begins by attaching event listeners and React state to the pre-rendered elements. The `window.__initialData__` object, injected in the server-rendered HTML, is used to bootstrap the client-side store.</p><p>To hydrate the application, we call</p><pre>import { hydrateRoot } from &#39;react-dom/client&#39;;<br>import App from &#39;./components/App&#39;;<br>import { configureStore } from &#39;./utils/client-utils&#39;;<br><br>const store = configureStore(window.__initialData__);<br>const container = document.getElementById(&#39;app&#39;);<br><br>hydrateRoot(container, &lt;App store={store} /&gt;);</pre><p>React ensures that the hydrated components take over the server-rendered content without unnecessary re-rendering.</p><h3>Conclusion</h3><p>Streaming SSR significantly enhances performance by improving first-paint times and reducing TTFB (Time to First Byte). This approach ensures a smooth user experience while keeping React’s declarative nature intact.</p><h4>Next Steps</h4><p>- Experiment with error boundaries for improved resilience.</p><p>- Optimize streaming performance with caching strategies.</p><p>- Combine streaming with lazy-loading for maximum efficiency.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=550864bee044" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goofy Things About Redux — Your All-Powerful State Management Library]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/goofy-things-about-redux-your-all-powerful-state-management-library-688c098fe7c3?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/688c098fe7c3</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 07:08:23 GMT</pubDate>
            <atom:updated>2025-02-05T07:08:23.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>Goofy Things About Redux — Your All-Powerful State Management Library</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*9-FdDydMZxjwNrAdNBa7Pg.png" /></figure><p>Many blogs explain how to use Redux, but few discuss what <strong>not</strong> to do when working with it. While Redux is a powerful state management tool, misusing it can lead to unnecessary complexity, performance issues, and poor application architecture. Here are some common pitfalls to avoid when using Redux.</p><h3>1. Using Redux for Everything</h3><p>One of the biggest mistakes developers make is putting <strong>every single piece of state</strong> into Redux. Redux is best suited for <strong>global state management</strong>, such as authentication, user preferences, or shared UI state. However, local component state (like form inputs, modal visibility, or temporary UI states) should remain in React’s useState or useReducer.</p><p>✅ Use Redux for:</p><ul><li>Authentication state</li><li>Caching API responses</li><li>Global UI settings (e.g., dark mode, language preference)</li></ul><p>❌ Avoid Redux for:</p><ul><li>Component-specific UI states</li><li>Form inputs that don’t need to be shared</li><li>State that doesn’t persist across renders</li></ul><h3>2. Mutating State Directly</h3><p>Redux follows the <strong>immutable state principle</strong>, meaning you should never mutate the existing state directly. Instead, always return a <strong>new</strong> object from your reducers.</p><p>❌ <strong>Bad Example (Mutating State):</strong></p><pre>const reducer = (state, action) =&gt; {<br>  state.user.name = action.payload; // ❌ Directly modifying state<br>  return state;<br>};</pre><p>✅ <strong>Good Example (Immutable Update):</strong></p><pre>const reducer = (state, action) =&gt; {<br>  return {<br>    ...state,<br>    user: { ...state.user, name: action.payload }, // ✅ Creating a new state object<br>  };<br>};</pre><p>Using libraries like <strong>Immer</strong> can make immutability easier:</p><pre>import produce from &quot;immer&quot;;<br>const reducer = (state, action) =&gt;<br>  produce(state, (draft) =&gt; {<br>    draft.user.name = action.payload; // ✅ Using Immer for immutable updates<br>  });</pre><h3>3. Too Many Reducers for Small Things</h3><p>It’s common to see developers create separate reducers for every tiny piece of state, leading to unnecessary complexity. Instead, <strong>group related states</strong> logically.</p><p>❌ <strong>Bad Example (Over-splitting reducers):</strong></p><pre>const userReducer = (state = {}, action) =&gt; { /* User logic */ };<br>const themeReducer = (state = &quot;light&quot;, action) =&gt; { /* Theme logic */ };<br>const sidebarReducer = (state = false, action) =&gt; { /* Sidebar logic */ };</pre><p>✅ <strong>Better Approach (Combine related state):</strong></p><pre>const uiReducer = (state = { theme: &quot;light&quot;, sidebarOpen: false }, action) =&gt; {<br>  switch (action.type) {<br>    case &quot;TOGGLE_SIDEBAR&quot;:<br>      return { ...state, sidebarOpen: !state.sidebarOpen };<br>    case &quot;CHANGE_THEME&quot;:<br>      return { ...state, theme: action.payload };<br>    default:<br>      return state;<br>  }<br>};</pre><h3>4. Dispatching Actions Inside Components Excessively</h3><p>It’s tempting to call dispatch directly inside components for every state update. However, doing this repeatedly can cause <strong>unnecessary re-renders</strong>.</p><p>❌ <strong>Bad Example (Multiple Dispatch Calls in a Component):</strong></p><pre>const handleChange = (e) =&gt; {<br>  dispatch({ type: &quot;UPDATE_NAME&quot;, payload: e.target.value });<br>};</pre><p>✅ <strong>Better Approach (Batch Updates in Thunks or Middleware)</strong></p><pre>const updateUser = (name) =&gt; (dispatch) =&gt; {<br>  dispatch({ type: &quot;UPDATE_NAME&quot;, payload: name });<br>  dispatch({ type: &quot;SAVE_TO_DATABASE&quot; });<br>};</pre><h3>5. Not Normalizing the State</h3><p>Storing deeply nested objects in Redux leads to <strong>difficult updates</strong> and <strong>poor performance</strong>. Instead, <strong>normalize the state structure</strong> like a relational database.</p><p>❌ <strong>Bad Example (Deeply Nested State):</strong></p><pre>const state = {<br>  users: {<br>    user1: {<br>      posts: [{ id: 1, title: &quot;Redux Mistakes&quot; }, { id: 2, title: &quot;React Hooks&quot; }]<br>    }<br>  }<br>};</pre><p>✅ <strong>Good Example (Normalized State):</strong></p><pre>const state = {<br>  users: { user1: { id: &quot;user1&quot;, name: &quot;John&quot; } },<br>  posts: { 1: { id: 1, title: &quot;Redux Mistakes&quot; }, 2: { id: 2, title: &quot;React Hooks&quot; } }<br>};</pre><p>Use libraries like <strong>normalizr</strong> to structure your state efficiently.</p><h3>6. Forgetting to Unsubscribe Listeners</h3><p>If you’re manually subscribing to the store using store.subscribe, always remember to <strong>unsubscribe</strong> when the component unmounts to avoid memory leaks.</p><p>❌ <strong>Bad Example (Forgetting Unsubscribe)</strong></p><pre>useEffect(() =&gt; {<br>  store.subscribe(() =&gt; console.log(store.getState()));<br>}, []);</pre><p>✅ <strong>Good Example (Unsubscribe on Cleanup)</strong></p><pre>useEffect(() =&gt; {<br>  const unsubscribe = store.subscribe(() =&gt; console.log(store.getState()));<br>  return () =&gt; unsubscribe(); // ✅ Clean up<br>}, []);</pre><h3>Final Thoughts</h3><p>Redux is a great tool when used correctly, but improper usage can lead to unnecessary complexity, performance issues, and frustration. By <strong>avoiding these common mistakes</strong>, you can make your Redux implementation more efficient, maintainable, and scalable.</p><p>What are some goofy mistakes <strong>you</strong> have made while using Redux? Let’s discuss in the comments!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*qaWqpWEHw22r5ySAYfTZ6A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=688c098fe7c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Broadcast Like a Boss: Building a PubSub Service for React Widgets!]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/broadcast-like-a-boss-building-a-pubsub-service-for-react-widgets-a9ea4c350046?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9ea4c350046</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[micro-front-end]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 06:48:55 GMT</pubDate>
            <atom:updated>2025-01-27T06:48:55.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Ever felt the pain of having multiple micro-apps in your React project that just refuse to talk to each other? You’re not alone! Whether it’s a widget that needs to update a page or a page that needs to inform widgets, inter-component communication can be a real headache in micro frontend setups.</p><p>In this article, I’ll walk you through how I built a slick PubSub service using BroadcastChannel to enable seamless communication between React widgets and the main page.</p><p>Spoiler: It’s simpler than you think and comes with zero dependency drama!</p><figure><img alt="“When your widgets finally start talking to your page and you’re feeling like the Merc with a Mouth!” 😎" src="https://cdn-images-1.medium.com/max/667/1*kVUWlFYKXFuJVaiWx78UJg.jpeg" /></figure><h3>The Challenge</h3><p>Here’s the setup:</p><ul><li><strong>Widgets and Page</strong>: Separate bundles, loaded independently.</li><li><strong>Communication Needs</strong>: Widgets need to send data to the page (like updating a count), and the page needs to broadcast events to widgets.</li><li><strong>Singleton Behavior</strong>: All widgets and the page should share the same communication channel without duplicating listeners.</li></ul><p>Initially, I considered SharedWorker, but browser support and setup complexities nudged me toward the unsung hero: BroadcastChannel.</p><h3>Why BroadcastChannel?</h3><p>BroadcastChannel is a native browser API designed for cross-context communication. It allows different scripts running in the same origin (e.g., tabs, iframes, or workers) to exchange messages effortlessly. Here’s why it’s awesome:</p><ul><li><strong>No Worker File Needed</strong>: Works out of the box without hosting a separate script.</li><li><strong>Simple API</strong>: Easy to implement with publish/subscribe patterns.</li><li><strong>Modern Browsers</strong>: Supported in all major browsers except IE (but who’s using that, anyway?).</li></ul><figure><img alt="“Deadpool getting ready to do some serious coding magic… Or maybe just Googling how BroadcastChannel works!” 😄" src="https://cdn-images-1.medium.com/max/1024/1*Ikf_jNbb44asovHJhNbrKA.jpeg" /></figure><h3>The Implementation</h3><h3>Step 1: Create the PubSub Service</h3><p>The heart of the implementation is a service file that encapsulates the BroadcastChannel logic. Here’s how it looks:</p><pre>// pubsubService.js<br>class PubSubService {<br>  constructor(channelName) {<br>    this.channel = new BroadcastChannel(channelName);<br>    this.listeners = {};<br><br>    // Listen for incoming messages<br>    this.channel.onmessage = (event) =&gt; {<br>      const { topic, data } = event.data;<br>      if (this.listeners[topic]) {<br>        this.listeners[topic].forEach((callback) =&gt; callback(data));<br>      }<br>    };<br>  }<br><br>  publish(topic, data) {<br>    this.channel.postMessage({ topic, data });<br>  }<br><br>  subscribe(topic, callback) {<br>    if (!this.listeners[topic]) {<br>      this.listeners[topic] = [];<br>    }<br>    this.listeners[topic].push(callback);<br>  }<br><br>  unsubscribe(topic, callback) {<br>    if (this.listeners[topic]) {<br>      this.listeners[topic] = this.listeners[topic].filter((cb) =&gt; cb !== callback);<br>    }<br>  }<br>}<br><br>export const pubSub = new PubSubService(&#39;myChannel&#39;);</pre><h3>Step 2: Integrate into Widgets and Page</h3><p>Both widgets and the page can import this service and start communicating like pros.</p><h4>Example: Widget</h4><pre>import { pubSub } from &#39;./pubsubService&#39;;<br><br>pubSub.subscribe(&#39;updateCount&#39;, (count) =&gt; {<br>  console.log(`Received updated count: ${count}`);<br>  // Update widget UI here<br>});<br><br>// Simulate a publish event<br>pubSub.publish(&#39;widgetReady&#39;, { widgetId: 1 });</pre><h4>Example: Page</h4><pre>import { pubSub } from &#39;./pubsubService&#39;;<br><br>// Publish event to notify widgets<br>pubSub.publish(&#39;updateCount&#39;, 42);<br><br>pubSub.subscribe(&#39;widgetReady&#39;, (data) =&gt; {<br>  console.log(`Widget Ready:`, data);<br>  // Update page UI here<br>});</pre><h3>Key Advantages</h3><p>Decoupled Communication: Widgets and the page don’t need direct references to each other.</p><p>Singleton Channel: Since BroadcastChannel is based on the channel name, it inherently ensures singleton behavior.</p><p>Easy Debugging: Messages are visible in the browser’s DevTools.</p><h3>Gotchas to Watch Out For</h3><ol><li><strong>Browser Support</strong>: While most modern browsers support BroadcastChannel, you’ll need polyfills or fallbacks for legacy browsers.</li><li><strong>Garbage Collection</strong>: Be sure to clean up listeners when components unmount to avoid memory leaks.</li></ol><pre>useEffect(() =&gt; {<br>  const callback = (data) =&gt; console.log(data);<br>  pubSub.subscribe(&#39;someEvent&#39;, callback);<br><br>  return () =&gt; {<br>    pubSub.unsubscribe(&#39;someEvent&#39;, callback);<br>  };<br>}, []);</pre><h3>Wrapping Up</h3><p>BroadcastChannel might not be the flashiest API, but it’s a powerful tool for enabling communication in micro-app setups. With this PubSub service, my widgets and page are finally in sync, and life is good.</p><p>If you’re struggling with similar communication woes, give BroadcastChannel a try—your React widgets will thank you!</p><p>Got questions or improvements? Drop them in the comments. Let’s geek out together!</p><figure><img alt="“When widgets and pages finally sync up, and Deadpool is ready to drop the mic!” 🎤😎" src="https://cdn-images-1.medium.com/max/570/1*4WMbEXRbog7TnSS5xX2mtw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9ea4c350046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is maintainable code performant?]]></title>
            <link>https://medium.com/@shubhankarmisra.bit/is-maintainable-code-performant-c1e5bf6908d1?source=rss-b450026aa6b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e5bf6908d1</guid>
            <dc:creator><![CDATA[Shubhankar Misra]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 06:30:27 GMT</pubDate>
            <atom:updated>2025-01-20T06:30:27.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*lGgpAVzzaqF9cr5YSG5RLA.png" /></figure><p>Yes, maintainable code is often more performant in the long term, even if it’s not inherently optimized for raw execution speed. Here’s how maintainable code contributes to performance:</p><h3>1. Ease of Optimization</h3><ul><li>Maintainable code, being clean and well-structured, makes it easier to identify performance bottlenecks and optimize specific areas.</li><li>Readable and modular code allows developers to pinpoint issues without navigating a mess of spaghetti code.</li></ul><h3>2. Bug Reduction</h3><ul><li>Cleaner code has fewer bugs, which can indirectly improve performance by avoiding scenarios like memory leaks, inefficient loops, or unnecessary computations.</li></ul><h3>3. Improved Scalability</h3><ul><li>Maintainable code is often designed with scalability in mind, meaning it performs well as the system grows.</li><li>Modular design and proper abstractions enable systems to handle increased load without degrading performance.</li></ul><h3>4. Facilitates Refactoring</h3><ul><li>When code is maintainable, it’s easier to refactor and adapt to new, more efficient algorithms or practices, leading to better performance over time.</li></ul><h3>5. Reusability and DRY (Don’t Repeat Yourself) Principle</h3><ul><li>Maintainable code often adheres to reusability, reducing redundancy. This can improve performance by avoiding duplicated logic and minimizing resource overhead.</li></ul><h3>6. Better Collaboration</h3><ul><li>Maintainable code is easier for teams to work on, enabling quicker implementation of performance fixes and features without introducing inefficiencies.</li></ul><h3>Caveat</h3><p>Maintainable code isn’t always the fastest in terms of execution speed initially. For instance:</p><ul><li>A highly optimized algorithm written in an overly complex way might outperform a cleanly written, naive implementation.</li><li>However, maintainable code has the advantage of being easily optimized or replaced when needed.</li></ul><p><strong>Conclusion</strong>: While maintainable code isn’t inherently the fastest, it lays a strong foundation for achieving performance gains in a sustainable and reliable way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e5bf6908d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>