<?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 Hareesh Dwivedi  on Medium]]></title>
        <description><![CDATA[Stories by Hareesh Dwivedi  on Medium]]></description>
        <link>https://medium.com/@hareeshdwivedi.vns.9198?source=rss-86083c5393c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GTdTK9fbtjVSN9HQtXW4sA.jpeg</url>
            <title>Stories by Hareesh Dwivedi  on Medium</title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198?source=rss-86083c5393c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 04:04:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hareeshdwivedi.vns.9198/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[Mistakes That Are Killing My Frontend Application]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/mistakes-that-are-killing-my-frontend-application-1f4b993ff170?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f4b993ff170</guid>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 18:16:06 GMT</pubDate>
            <atom:updated>2026-09-01T18:16:06.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wpQ04EwyUknuWAI4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rjoWfjQ4bE7TvsXB" /></figure><h3>17 Frontend Architecture Mistakes I’ve Learned to Fear After 10+ Years of Building Production Applications</h3><p>There is a stage in every frontend developer’s career when writing code is no longer the difficult part.</p><p>The difficult part is <strong>deciding where that code should live, who should own it, how it should communicate with the rest of the application, and what happens when it eventually needs to change.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4YN1Qrhdv1B7arbi" /></figure><p>Early in my career, I used to think good frontend architecture meant:</p><ul><li>clean folders</li><li>reusable components</li><li>a state management library</li><li>unit tests</li><li>good naming</li><li>a design system</li></ul><p>After working on large applications and seeing architectures evolve over years, I think differently.</p><p>The biggest frontend problems rarely come from one terrible decision.</p><p>They come from <strong>small decisions that looked reasonable at the time</strong>.</p><pre>               Small Shortcut<br>                         │<br>                         ▼<br>                  &quot;Just for now...&quot;<br>                         │<br>                         ▼<br>                   Another Feature<br>                         │<br>                         ▼<br>                  Another Exception<br>                         │<br>                         ▼<br>                  More Dependencies<br>                         │<br>                         ▼<br>                 Architecture Drift<br>                         │<br>                         ▼<br>                 ┌───────────────┐<br>                 │ Slow Delivery │<br>                 │ More Bugs     │<br>                 │ Hard Testing  │<br>                 │ Poor UX       │<br>                 └───────────────┘</pre><p>And eventually someone asks:</p><blockquote><em>“Why is this frontend so difficult to change?”</em></blockquote><p>This article is about those decisions.</p><p>Not theoretical architecture.</p><p>Not another “10 React best practices” list.</p><p>These are the kinds of problems that show up when a frontend application grows from a few developers to multiple teams, multiple environments, hundreds of components, dozens of APIs, and years of accumulated changes.</p><h3>Before We Start: Architecture Doesn’t Usually Break Overnight</h3><p>A frontend application rarely becomes unmaintainable in one sprint.</p><p>It usually looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-LvMtvVVaVinUEAl" /></figure><pre>Year 1<br>│<br>├── Simple components<br>├── Small state<br>├── Few APIs<br>└── Fast releases<br>        │<br>        ▼<br>Year 2<br>│<br>├── More features<br>├── More developers<br>├── More shared components<br>└── More global state<br>        │<br>        ▼<br>Year 3<br>│<br>├── Multiple teams<br>├── Complex workflows<br>├── Increasing dependencies<br>├── Slow CI<br>└── Performance issues<br>        │<br>        ▼<br>Year 4<br>│<br>├── Micro-frontends discussion<br>├── Huge shared components<br>├── Technical debt<br>├── Flaky tests<br>└── Fear of refactoring</pre><p>The application didn’t suddenly become bad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kLC5p_hkiZOG3TpV" /></figure><p><strong>The architecture accumulated decisions.</strong></p><h3>Mistake #1 — Putting Everything in Redux</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*t1XCfEawddIiBjf0" /></figure><p>Let’s start with one of the most common mistakes in React applications.</p><p>Redux is not the problem.</p><p><strong>Using Redux as the answer to every state problem is the problem.</strong></p><p>I’ve seen applications where developers put:</p><pre>User<br>Cart<br>Products<br>Modal<br>Dropdown<br>Form<br>Filters<br>API response<br>Loading state<br>Notifications<br>Selected tab<br>Temporary UI state</pre><p>all into Redux.</p><p>The architecture eventually looks like:</p><pre>                         Redux Store<br>                             │<br>        ┌────────────────────┼────────────────────┐<br>        ▼                    ▼                    ▼<br>     authSlice           cartSlice           uiSlice<br>        │                    │                    │<br>        ▼                    ▼                    ▼<br>    user state          product state        modal state<br>        │                    │                    │<br>        └────────────────────┼────────────────────┘<br>                             ▼<br>                     Hundreds of consumers</pre><p>Now a developer wants to change one small piece of UI state.</p><p>They have to understand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*nsT4a4Trg0oDhUFV" /></figure><pre>Component<br>   ↓<br>Action<br>   ↓<br>Reducer<br>   ↓<br>Selector<br>   ↓<br>Middleware<br>   ↓<br>Store<br>   ↓<br>Component</pre><p>For something that could have been:</p><pre>const [isOpen, setIsOpen] = useState(false);</pre><h3>Real-world scenario</h3><p>A filter drawer on an analytics dashboard gets placed in Redux because “other pages might need the filters.”</p><p>Six months later:</p><ul><li>filters persist unexpectedly</li><li>navigation resets them incorrectly</li><li>different dashboards interpret the same filter differently</li><li>selectors become complicated</li><li>developers are afraid to remove the state</li></ul><p>The original decision took five minutes.</p><p>The architectural cost lasted months.</p><h3>Better approach</h3><p>Classify state first:</p><pre>                     State<br>                       │<br>       ┌───────────────┼────────────────┐<br>       ▼               ▼                ▼<br>   Local UI       Server State      Global State<br>       │               │                │<br>    useState      Query/Cache         Redux</pre><p>Ask:</p><blockquote><em>Who owns this state?</em></blockquote><p>That’s usually a better question than:</p><blockquote><em>Should this go into Redux?</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C6Nx1ZEfy3oS8sq9" /></figure><h3>Mistake #2 — The Giant utils Folder</h3><p>Every application eventually gets one.</p><pre>utils/<br>├── formatDate.ts<br>├── calculatePrice.ts<br>├── userHelper.ts<br>├── orderHelper.ts<br>├── permissionHelper.ts<br>├── apiHelper.ts<br>├── dashboardHelper.ts<br>├── exportHelper.ts<br>├── validationHelper.ts<br>└── ...</pre><p>At first it feels organized.</p><p>Then utils becomes the most difficult folder in the repository.</p><p>Why?</p><p>Because it has <strong>no domain ownership</strong>.</p><p>Consider:</p><pre>calculateOrderTotal()</pre><p>Is that a utility?</p><p>Probably not.</p><p>It’s business logic.</p><p>It should probably live closer to:</p><pre>features/<br>└── orders/<br>    ├── components/<br>    ├── services/<br>    ├── hooks/<br>    ├── state/<br>    └── domain/<br>        └── calculateOrderTotal.ts</pre><h3>The rule I learned</h3><blockquote><em>If a piece of logic belongs to a business domain, keep it close to that domain.</em></blockquote><p>A utility should generally be:</p><ul><li>generic</li><li>reusable</li><li>domain-independent</li><li>predictable</li></ul><h3>Warning sign</h3><p>If your utils folder needs a README explaining where things belong, you probably have an ownership problem.</p><h3>Mistake #3 — Building a “God Component”</h3><p>This is one of the most expensive mistakes in large React applications.</p><p>It starts as:</p><pre>Dashboard.tsx</pre><p>Then requirements arrive.</p><pre>Dashboard<br> ├── Header<br> ├── Filters<br> ├── Charts<br> ├── Map<br> ├── Table<br> ├── Export<br> ├── Notifications<br> ├── Permissions<br> ├── API calls<br> ├── WebSocket<br> ├── Analytics<br> └── Feature flags</pre><p>Eventually:</p><pre>Dashboard.tsx<br>   ↓<br>2,000+ lines<br>   ↓<br>20 useEffects<br>   ↓<br>15 API calls<br>   ↓<br>12 pieces of local state<br>   ↓<br>Redux interactions<br>   ↓<br>Conditional rendering everywhere</pre><p>The worst part isn’t the file size.</p><p>It’s the coupling.</p><pre>                Dashboard<br>                     │<br>      ┌──────────────┼──────────────┐<br>      ▼              ▼              ▼<br>    API             Redux          UI<br>      │              │              │<br>      └──────────────┼──────────────┘<br>                     │<br>                     ▼<br>               Everything depends<br>                  on everything</pre><h3>Real-world failure</h3><p>A developer changes the dashboard filter.</p><p>The chart breaks.</p><p>Another developer fixes the chart.</p><p>The table starts showing stale data.</p><p>A third developer modifies the API transformation.</p><p>Export functionality breaks.</p><p>Nobody intentionally designed this mess.</p><p>It emerged because the component became the <strong>integration point for everything</strong>.</p><h3>Better architecture</h3><pre>Dashboard<br>│<br>├── DashboardHeader<br>├── DashboardFilters<br>├── DashboardMetrics<br>├── DashboardCharts<br>├── DashboardTable<br>└── DashboardExport</pre><p>Each feature owns its behaviour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oDl37RzfFQjkL7qV" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3MWQ9Q8C_bRKVwdn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZzdCOWwP_lFjWyr-" /></figure><p>The parent coordinates.</p><p>It doesn’t need to understand every internal detail.</p><h3>Mistake #4 — Overusing Custom Hooks</h3><p>Custom hooks are powerful.</p><p>But abstraction has a cost.</p><p>I’ve seen:</p><pre>useUser()<br>useUserData()<br>useUserProfile()<br>useUserActions()<br>useUserPermissions()<br>useUserManager()<br>useUserController()</pre><p>The application has technically become “cleaner.”</p><p>But developers now spend more time navigating abstractions.</p><h3>A useful test</h3><p>Before creating a hook, ask:</p><blockquote><em>Is this behaviour reused?</em></blockquote><blockquote><em>Is the logic complex enough to deserve isolation?</em></blockquote><blockquote><em>Does the hook represent a meaningful concept?</em></blockquote><p>If the answer is no, keep the logic local.</p><h3>Bad abstraction</h3><pre>Component<br>   ↓<br>useButtonState()<br>   ↓<br>useInternalState()<br>   ↓<br>useButtonController()<br>   ↓<br>useButtonManager()</pre><h3>Better abstraction</h3><pre>Checkout<br>   ↓<br>useCheckout()<br>   ↓<br>Cart + Payment + Validation</pre><p>The difference is <strong>domain meaning</strong>.</p><h3>Mistake #5 — Context Becoming the New Redux</h3><p>Context starts as:</p><pre>ThemeProvider</pre><p>Then:</p><pre>AuthProvider</pre><p>Then:</p><pre>UserProvider</pre><p>Then:</p><pre>CartProvider</pre><p>Then:</p><pre>NotificationProvider</pre><p>Then:</p><pre>DashboardProvider</pre><p>Eventually:</p><pre>&lt;App&gt;<br>  &lt;AuthProvider&gt;<br>    &lt;UserProvider&gt;<br>      &lt;CartProvider&gt;<br>        &lt;NotificationProvider&gt;<br>          &lt;DashboardProvider&gt;<br>             ...</pre><p>Now every developer is afraid to touch the provider tree.</p><h3>Context is excellent for dependency sharing.</h3><p>It is not automatically a full state-management strategy.</p><p>Use the right tool for the problem.</p><h3>Mistake #6 — No Clear Feature Boundaries</h3><p>One of the strongest architectural patterns I’ve seen in growing applications is <strong>feature ownership</strong>.</p><p>Compare:</p><pre>components/<br>hooks/<br>services/<br>utils/<br>types/</pre><p>with:</p><pre>features/<br>├── authentication/<br>├── orders/<br>├── payments/<br>├── products/<br>└── dashboard/</pre><p>The second structure answers a critical question:</p><blockquote><strong><em>Who owns this code?</em></strong></blockquote><p>A feature boundary should ideally define:</p><pre>Feature<br> │<br> ├── UI<br> ├── State<br> ├── API<br> ├── Business Logic<br> ├── Tests<br> └── Types</pre><p>Not every project needs strict feature-based architecture.</p><p>But every large project needs <strong>some form of ownership boundary</strong>.</p><h3>Mistake #7 — Creating a Shared Component for Everything</h3><p>“Make it reusable.”</p><p>Sounds like good engineering.</p><p>But premature reuse can create enormous complexity.</p><p>Imagine:</p><pre>Button</pre><p>becomes:</p><pre>Button<br>├── primary<br>├── secondary<br>├── danger<br>├── outline<br>├── ghost<br>├── compact<br>├── large<br>├── loading<br>├── icon<br>├── dashboard<br>├── checkout<br>├── legacy<br>└── tenantSpecific</pre><p>Then someone adds:</p><pre>specialCase</pre><p>and another developer adds:</p><pre>disablePadding</pre><p>Eventually:</p><pre>&lt;Button<br>  variant=&quot;primary&quot;<br>  size=&quot;small&quot;<br>  compact<br>  loading<br>  dashboardMode<br>  legacy<br>  disablePadding<br>  customSpacing<br>  specialCase<br>/&gt;</pre><p>This isn’t reuse.</p><p>It’s <strong>configuration complexity</strong>.</p><h3>My rule</h3><p>Don’t ask:</p><blockquote><em>Can we reuse this?</em></blockquote><p>Ask:</p><blockquote><strong><em>Should these things have the same abstraction?</em></strong></blockquote><p>Those are very different questions.</p><h3>Mistake #8 — Premature Micro-Frontends</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/0*iyVEZK90drsZ51L4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cx5E2F1iDta0Ojwl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t-mUM9iO35WDVjra" /></figure><p>Micro-frontends can solve real problems.</p><p>But “our application is large” isn’t automatically one of them.</p><p>A useful decision model is:</p><pre>                      Large Application<br>                           │<br>                           ▼<br>                  Are teams independent?<br>                       /         \<br>                     No           Yes<br>                     │             │<br>                     ▼             ▼<br>              Modular Monolith   Continue<br>                                   │<br>                                   ▼<br>                          Independent releases?<br>                              /          \<br>                            No            Yes<br>                            │              │<br>                            ▼              ▼<br>                       Stay Modular   Consider MFE</pre><p>Micro-frontends introduce:</p><ul><li>deployment complexity</li><li>shared dependency management</li><li>runtime failures</li><li>routing challenges</li><li>authentication coordination</li><li>cross-application communication</li><li>version compatibility</li><li>performance overhead</li></ul><h3>The lesson</h3><blockquote><em>Micro-frontends are often an organizational architecture decision disguised as a technical decision.</em></blockquote><p>If five teams need independent deployment and ownership, they may make sense.</p><p>If one team owns the entire application, they may create more problems than they solve.</p><h3>Mistake #9 — Turning the Design System Into a Monster</h3><p>A design system should provide <strong>constraints and consistency</strong>.</p><p>It shouldn’t attempt to solve every possible business requirement.</p><p>A healthy model:</p><pre>Design Tokens<br>     │<br>     ▼<br>Primitives<br>     │<br>     ▼<br>Reusable Components<br>     │<br>     ▼<br>Feature Composition</pre><p>An unhealthy model:</p><pre>Design System<br>      │<br>      ├── Business Rules<br>      ├── API Calls<br>      ├── Permissions<br>      ├── Routing<br>      ├── Feature Flags<br>      └── Every possible UI variation</pre><p>The second system becomes extremely difficult to evolve.</p><h3>The rule</h3><blockquote><em>Shared components should provide capabilities, not own your entire business.</em></blockquote><h3>Mistake #10 — No Error Boundaries or Failure Strategy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kt9QR00xWo140ooA" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H8AA-Ku_52sRNerR" /></figure><p>A frontend should assume things will fail.</p><p>APIs fail.</p><p>JavaScript fails.</p><p>Third-party services fail.</p><p>Network connections disappear.</p><p>Data becomes invalid.</p><p>A component crashes.</p><p>The question isn’t:</p><blockquote><em>Will something fail?</em></blockquote><p>The question is:</p><blockquote><strong><em>What does the user see when it fails?</em></strong></blockquote><p>Consider:</p><pre>Application<br>│<br>├── Header<br>├── Navigation<br>├── Dashboard<br>│    ├── Revenue<br>│    ├── Orders<br>│    └── Analytics<br>└── Notifications</pre><p>If Analytics crashes, should the entire application disappear?</p><p>Usually not.</p><p>A resilient architecture isolates failure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YXV30_ZKXlLLPU0o" /></figure><pre>Application<br>│<br>├── Header<br>├── Navigation<br>│<br>├── Dashboard<br>│    ├── Revenue<br>│    ├── Orders<br>│    └── Analytics<br>│          │<br>│          ▼<br>│    Error Boundary<br>│          │<br>│          ▼<br>│    &quot;Analytics unavailable&quot;<br>│<br>└── Notifications</pre><p>The rest of the application remains usable.</p><h3>Mistake #11 — Treating API Errors as an Afterthought</h3><p>I’ve seen frontend implementations designed around:</p><pre>200 → render data</pre><p>But production doesn’t work that way.</p><p>A realistic state model is:</p><pre>API<br>│<br>├── 200 → Success<br>├── 204 → Empty<br>├── 400 → Validation<br>├── 401 → Authentication<br>├── 403 → Permission<br>├── 404 → Not Found<br>├── 409 → Conflict<br>├── 429 → Rate Limited<br>├── 500 → Server Error<br>├── Timeout<br>└── Network Failure</pre><p>Each state can require a different UX.</p><p>API State || Expected UI<br>Loading Skeleton<br>Success Data<br>Empty Empty state<br>400 Validation message<br>401 Login / refresh<br>403 Permission message<br>404 Not found<br>409 Conflict resolution<br>429 Retry / rate-limit message<br>500 Error state<br>Network failure Retry<br>Slow API Loading indicator</p><p>This isn’t just API handling.</p><p>It’s <strong>product behaviour</strong>.</p><h3>Mistake #12 — Making the Frontend Compensate for a Bad API</h3><p>Here’s a pattern that becomes expensive quickly.</p><pre>Backend Response<br>       │<br>       ▼<br>Frontend Transformation<br>       │<br>       ▼<br>Another Transformation<br>       │<br>       ▼<br>Redux Mapping<br>       │<br>       ▼<br>Component Mapping<br>       │<br>       ▼<br>UI</pre><p>One API returns:</p><pre>{<br>  &quot;user_name&quot;: &quot;John&quot;<br>}</pre><p>Another:</p><pre>{<br>  &quot;userName&quot;: &quot;John&quot;<br>}</pre><p>Another:</p><pre>{<br>  &quot;name&quot;: &quot;John&quot;<br>}</pre><p>Now the frontend has three different models for the same concept.</p><h3>Real-world consequence</h3><p>The frontend becomes a translation engine.</p><p>Every feature creates another adapter.</p><p>Eventually nobody knows which model is canonical.</p><h3>Better approach</h3><p>Create a clear boundary:</p><pre>External API<br>     │<br>     ▼<br>API Adapter<br>     │<br>     ▼<br>Frontend Domain Model<br>     │<br>     ▼<br>Application</pre><p>The application should ideally not know every weirdness of every backend service.</p><h3>Mistake #13 — No Performance Budget</h3><p>Performance usually dies slowly.</p><pre>New Feature<br>     ↓<br>New Library<br>     ↓<br>New Dependency<br>     ↓<br>New JavaScript<br>     ↓<br>Larger Bundle<br>     ↓<br>More Parsing<br>     ↓<br>More Execution<br>     ↓<br>Slower Interaction</pre><p>Then six months later:</p><blockquote><em>“Why is the dashboard so slow?”</em></blockquote><h3>Performance should be an architectural concern.</h3><p>Think about:</p><pre>                   Performance<br>                      │<br>       ┌──────────────┼──────────────┐<br>       ▼              ▼              ▼<br>    Network        JavaScript      Rendering<br>       │              │              │<br>      CDN          Bundle size     React work<br>      Cache        Code split      DOM size<br>      API          Tree shake      Virtualization<br>       │              │              │<br>       └──────────────┼──────────────┘<br>                      ▼<br>                  User UX</pre><p>Measure:</p><ul><li>Core Web Vitals</li><li>bundle size</li><li>long tasks</li><li>API latency</li><li>memory usage</li><li>rendering cost</li><li>third-party scripts</li></ul><p>The exact thresholds depend on the application.</p><p>But there should be <strong>some thresholds</strong>.</p><h3>Mistake #14 — Testing Implementation Instead of Behaviour</h3><p>This is one of the easiest ways to build a large but weak test suite.</p><p>Bad test:</p><pre>Component<br>   ↓<br>Check CSS class<br>   ↓<br>Check internal state<br>   ↓<br>Check private function</pre><p>Better test:</p><pre>User<br>  ↓<br>Interaction<br>  ↓<br>Application behaviour<br>  ↓<br>Expected result</pre><p>For example:</p><pre>Enter credentials<br>       ↓<br>Click Login<br>       ↓<br>API request<br>       ↓<br>Loading state<br>       ↓<br>Successful response<br>       ↓<br>Dashboard displayed</pre><p>The test protects the <strong>user journey</strong>.</p><p>Not the implementation.</p><h3>Mistake #15 — Treating 100% Test Coverage as Quality</h3><p>A project can have:</p><pre>98% coverage</pre><p>and still have terrible tests.</p><p>Coverage tells you:</p><blockquote><em>Which code executed?</em></blockquote><p>It doesn’t necessarily tell you:</p><blockquote><em>Did we test the important behaviour?</em></blockquote><p>Imagine:</p><pre>Authentication     → 98%<br>Checkout           → 95%<br>Payment failure    → 0%<br>Permission flow    → 0%<br>Critical E2E       → 0%</pre><p>The number looks impressive.</p><p>The product isn’t necessarily protected.</p><h3>Better metrics</h3><p>Track:</p><pre>Critical Journey Coverage<br>Defect Escape Rate<br>Flaky Test Rate<br>Test Execution Time<br>Production Regression Rate<br>Mean Time to Diagnose</pre><p>Coverage is useful.</p><p><strong>It just shouldn’t be the goal.</strong></p><h3>Mistake #16 — Ignoring Accessibility Until QA</h3><p>Another common pattern:</p><pre>Build UI<br>   ↓<br>Make it look correct<br>   ↓<br>Finish feature<br>   ↓<br>QA<br>   ↓<br>Accessibility issues discovered<br>   ↓<br>Rewrite component</pre><p>That’s expensive.</p><p>Accessibility should influence component design from the beginning.</p><p>For a dialog, think about:</p><pre>Dialog<br>│<br>├── Focus management<br>├── Keyboard navigation<br>├── Escape behaviour<br>├── Accessible name<br>├── Screen reader semantics<br>└── Focus restoration</pre><p>For forms:</p><pre>Input<br>│<br>├── Label<br>├── Error message<br>├── Required state<br>├── Keyboard navigation<br>└── Accessible description</pre><p>Accessibility isn’t a QA phase.</p><p><strong>It’s part of component architecture.</strong></p><h3>Mistake #17 — No Observability in Production</h3><p>This is one of the biggest differences between a junior and senior mindset.</p><p>A frontend isn’t finished when it passes CI.</p><p>It needs to be observable in production.</p><pre>                 Application<br>                      │<br>                      ▼<br>                 Production<br>                      │<br>        ┌─────────────┼─────────────┐<br>        ▼             ▼             ▼<br>      Errors         RUM        API Metrics<br>        │             │             │<br>        ▼             ▼             ▼<br>    Exceptions    Web Vitals     Latency<br>        │             │             │<br>        └─────────────┼─────────────┘<br>                      ▼<br>                Engineering<br>                      │<br>                      ▼<br>                Improvements</pre><p>You should be able to answer:</p><ul><li>Which release introduced the problem?</li><li>Which browsers are affected?</li><li>Which users are affected?</li><li>Is the problem frontend or backend?</li><li>Did API latency increase?</li><li>Did a bundle change cause it?</li><li>Is a specific route failing?</li></ul><p>Without observability, production debugging becomes guesswork.</p><h3>Mistake #18 — Ignoring Dependency Risk</h3><p>Modern frontend applications can have hundreds of dependencies.</p><pre>Application<br>│<br>├── React<br>├── Router<br>├── UI Library<br>├── Charts<br>├── Date Library<br>├── HTTP Client<br>├── Analytics<br>├── Monitoring<br>├── Testing<br>└── ...</pre><p>Each dependency introduces:</p><ul><li>security risk</li><li>bundle cost</li><li>upgrade cost</li><li>maintenance risk</li><li>compatibility risk</li></ul><p>Before adding a package, ask:</p><pre>Do we really need it?<br>       │<br>       ├── Can existing code solve it?<br>       │<br>       ├── Can a browser API solve it?<br>       │<br>       ├── What&#39;s the bundle cost?<br>       │<br>       ├── Is it maintained?<br>       │<br>       └── What happens if it is abandoned?</pre><p>One of the most expensive dependencies is often the one you didn’t need.</p><h3>Mistake #19 — Circular Dependencies</h3><p>This problem usually appears after years of growth.</p><pre>Feature A<br>   ↓<br>Shared<br>   ↓<br>Feature B<br>   ↓<br>Feature A</pre><p>Now the boundaries aren’t real.</p><p>A better architecture should have dependency direction.</p><pre>               App<br>                 │<br>        ┌────────┴────────┐<br>        ▼                 ▼<br>    Features           Infrastructure<br>        │<br>        ▼<br>     Shared<br>        │<br>        ▼<br>     Primitives</pre><p>Ideally, lower-level modules shouldn’t depend back on higher-level features.</p><h3>The question to ask</h3><blockquote><em>Can I draw the dependency direction?</em></blockquote><p>If you cannot, the architecture may already be too coupled.</p><h3>Mistake #20 — No Definition of Done for Frontend Quality</h3><p>A feature isn’t really complete because:</p><pre>Code merged ✓</pre><p>A mature definition of done might include:</p><pre>Feature<br>│<br>├── Functional behaviour<br>├── Loading state<br>├── Empty state<br>├── Error state<br>├── Accessibility<br>├── Responsive behaviour<br>├── Unit / integration tests<br>├── Critical E2E coverage<br>├── Performance considerations<br>├── Analytics / observability<br>└── Documentation</pre><p>Not every feature requires every item.</p><p>But the team should consciously decide.</p><h3>The Architecture I Prefer Today</h3><p>After years of frontend development, I don’t believe in one magical folder structure or one magical library.</p><p>I prefer <strong>clear boundaries</strong>.</p><p>A large React/Next.js application might look conceptually like:</p><pre>┌──────────────────────────────────────────────────────┐<br>│                    APPLICATION                       │<br>│                                                      │<br>│  ┌──────────┐ ┌──────────┐ ┌──────────┐              │<br>│  │   Auth   │ │  Orders  │ │Dashboard │              │<br>│  │ Feature  │ │ Feature  │ │ Feature  │              │<br>│  └────┬─────┘ └────┬─────┘ └────┬─────┘              │<br>│       │             │             │                  │<br>│       └─────────────┼─────────────┘                  │<br>│                     ▼                                │<br>│              ┌──────────────┐                        │<br>│              │ Shared UI    │                        │<br>│              │ &amp; Primitives │                        │<br>│              └──────┬───────┘                        │<br>│                     │                                │<br>│              ┌──────▼───────┐                        │<br>│              │ Infrastructure│                       │<br>│              │ API / Auth   │                        │<br>│              │ Monitoring   │                        │<br>│              └──────────────┘                        │<br>└──────────────────────────────────────────────────────┘</pre><p>And each feature should have clear ownership:</p><pre>features/<br>│<br>├── authentication/<br>│   ├── components/<br>│   ├── hooks/<br>│   ├── services/<br>│   ├── state/<br>│   ├── domain/<br>│   └── tests/<br>│<br>├── orders/<br>│   ├── components/<br>│   ├── hooks/<br>│   ├── services/<br>│   ├── state/<br>│   ├── domain/<br>│   └── tests/<br>│<br>└── dashboard/<br>    ├── components/<br>    ├── hooks/<br>    ├── services/<br>    ├── state/<br>    ├── domain/<br>    └── tests/</pre><p>Again, the exact folder structure isn’t the important part.</p><p><strong>The boundaries are.</strong></p><h3>The 10 Questions I Ask Before Approving Frontend Architecture</h3><p>After enough experience, architecture reviews become less about arguing over libraries and more about asking questions.</p><h3>1. Who owns this state?</h3><p>If nobody knows, that’s a problem.</p><h3>2. Who owns this component?</h3><p>Shared code without ownership becomes dangerous.</p><h3>3. What is the business boundary?</h3><p>If everything belongs everywhere, nothing has a boundary.</p><h3>4. What happens when this fails?</h3><p>If the answer is “the user gets a blank page,” redesign it.</p><h3>5. How will we test this?</h3><p>If it’s extremely difficult to test, examine the design.</p><h3>6. What happens when traffic increases?</h3><p>Performance shouldn’t be discovered after production traffic arrives.</p><h3>7. What happens when the API changes?</h3><p>Define contracts and adapters.</p><h3>8. What happens when another team needs this?</h3><p>Design for ownership, not just reuse.</p><h3>9. What happens six months from now?</h3><p>This is one of the most important questions.</p><h3>10. Are we solving today’s problem or predicting tomorrow’s?</h3><p>This question prevents a lot of over-engineering.</p><h3>The Senior Engineer’s Architecture Checklist</h3><p>Before introducing another library, abstraction, provider, shared component, or micro-frontend, ask:</p><pre>                   New Requirement<br>                           │<br>                           ▼<br>                 What problem are we<br>                     solving?<br>                           │<br>             ┌─────────────┴─────────────┐<br>             ▼                           ▼<br>        Existing solution?          New solution?<br>             │                           │<br>             ▼                           ▼<br>          Reuse                    Is complexity<br>                                    justified?<br>                                        │<br>                              ┌─────────┴─────────┐<br>                              ▼                   ▼<br>                             No                  Yes<br>                              │                   │<br>                              ▼                   ▼<br>                           Simplify           Introduce<br>                                               carefully</pre><p>This sounds simple.</p><p>In large applications, it can save months.</p><h3>What 10+ Years Has Changed for Me</h3><p>Earlier in my career, I often optimized for:</p><blockquote><strong><em>“How quickly can I implement this?”</em></strong></blockquote><p>With experience, the question changed to:</p><blockquote><strong><em>“How quickly can the team safely change this six months from now?”</em></strong></blockquote><p>That’s a very different mindset.</p><p>I don’t automatically reject:</p><ul><li>Redux</li><li>Context</li><li>Micro-frontends</li><li>Design systems</li><li>Custom hooks</li><li>abstractions</li><li>shared components</li></ul><p>All of them can be excellent tools.</p><p>The problem starts when the tool becomes the architecture.</p><h3>The Biggest Lesson</h3><p>If I had to reduce everything in this article to one diagram, it would be this:</p><pre>                       Business Requirement<br>                            │<br>                            ▼<br>                    ┌──────────────┐<br>                    │ Simple Design│<br>                    └──────┬───────┘<br>                           │<br>                           ▼<br>                    Clear Ownership<br>                           │<br>                           ▼<br>                    Clear Boundaries<br>                           │<br>                           ▼<br>                      Testability<br>                           │<br>                           ▼<br>                      Resilience<br>                           │<br>                           ▼<br>                      Performance<br>                           │<br>                           ▼<br>                    Observability<br>                           │<br>                           ▼<br>                    Maintainability<br>                           │<br>                           ▼<br>                 Sustainable Frontend</pre><p>Not every application needs micro-frontends.</p><p>Not every application needs Redux.</p><p>Not every component needs to be reusable.</p><p>Not every function needs a custom hook.</p><p>Not every piece of state needs global management.</p><p>Not every line needs a test.</p><p>And not every abstraction makes your application better.</p><h3>Final Thoughts</h3><p>After 10+ years, the biggest frontend architecture lesson I’ve learned is this:</p><blockquote><strong><em>Complexity is easy to add and extremely expensive to remove.</em></strong></blockquote><p>A five-minute shortcut can become a six-month maintenance problem.</p><p>A “temporary” workaround can become a permanent API.</p><p>A reusable component can become a 50-prop monster.</p><p>A global state decision can become impossible to reverse.</p><p>A missing error boundary can become a production incident.</p><p>A missing performance budget can become a user-retention problem.</p><p>And a lack of ownership can make an entire engineering organization slower.</p><p>The goal of frontend architecture isn’t to create the most sophisticated system.</p><p>It’s to create a system where:</p><pre>Developer<br>    │<br>    ▼<br>Understands the boundary<br>    │<br>    ▼<br>Finds the owner<br>    │<br>    ▼<br>Makes the change<br>    │<br>    ▼<br>Runs the tests<br>    │<br>    ▼<br>Deploys safely<br>    │<br>    ▼<br>Observes production<br>    │<br>    ▼<br>Improves the system</pre><p>That’s what scalable frontend architecture looks like to me.</p><p>Not the number of technologies in package.json.</p><p>Not the number of folders in src.</p><p>Not whether the project uses Redux, Zustand, Context, Next.js, Module Federation, or something else.</p><p><strong>The real measure of architecture is how safely and predictably your team can change the application.</strong></p><p>And perhaps the most important question to ask during your next architecture review is:</p><blockquote><strong><em>“Are we making this application easier to change — or just more complicated to build?”</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f4b993ff170" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro-Frontends: The Architecture Everyone Talks About but Few Truly Understand]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/micro-frontends-the-architecture-everyone-talks-about-but-few-truly-understand-45d4e340562a?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/45d4e340562a</guid>
            <category><![CDATA[react-architecture]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[microfrontend-vs-monolith]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 14:52:58 GMT</pubDate>
            <atom:updated>2026-08-31T14:52:58.193Z</atom:updated>
            <content:encoded><![CDATA[<h3>Micro-Frontends: When You Need Them and When You Don’t</h3><blockquote><strong><em>The most important lesson:</em></strong><em> Micro-frontends are not primarily a frontend technology. They are an organizational and deployment architecture.</em></blockquote><blockquote><em>If your problem is “our React application has 500 components,” micro-frontends probably aren’t the answer.</em></blockquote><blockquote><em>If your problem is “eight teams cannot release independently because every change requires coordination,” now we have an interesting architectural problem.</em></blockquote><h3>1. After 10+ Years, This Is How I Look at Micro-Frontends</h3><p>I’ve seen frontend architectures go through roughly this evolution:</p><pre>Server-rendered pages<br>        ↓<br>jQuery / server templates<br>        ↓<br>SPA<br>        ↓<br>Large SPA / Frontend Monolith<br>        ↓<br>Modular Monolith<br>        ↓<br>Micro-Frontends</pre><p>And the important part is:</p><p><strong>Micro-frontends are not necessarily the next step.</strong></p><p>A lot of teams make this mistake:</p><pre>Application is getting big<br>        ↓<br>Let&#39;s introduce micro-frontends</pre><p>I would instead ask:</p><pre>Why is the application becoming difficult to change?<br>        ↓<br>Is the problem code?<br>Is it ownership?<br>Is it deployment?<br>Is it team coordination?<br>Is it build time?<br>Is it technology migration?<br>Is it organizational structure?</pre><p>Because the solution depends on the answer.</p><p>For example, if you have:</p><ul><li>10 developers</li><li>one React application</li><li>one deployment pipeline</li><li>one product</li><li>one release cadence</li></ul><p>I would probably <strong>not</strong> introduce micro-frontends.</p><p>A well-designed modular monolith may be significantly better.</p><p>But if you have:</p><ul><li>100+ frontend engineers</li><li>10 autonomous teams</li><li>different business domains</li><li>independent release requirements</li><li>legacy + modern frameworks</li><li>multiple products being brought together</li></ul><p>then micro-frontends become much more interesting.</p><p>This is consistent with the modern guidance from Nx as well: the strongest reason to adopt micro-frontends is <strong>independent deployment</strong>, not simply having a large codebase. (<a href="https://nx.dev/docs/kb/micro-frontend-architecture?utm_source=chatgpt.com">Nx</a>)</p><h3>2. What Problem Are We Actually Solving?</h3><p>Imagine an e-commerce application:</p><pre>                    E-Commerce<br>                         |<br>       +-----------------+------------------+<br>       |                 |                  |<br>    Catalog            Cart             Checkout<br>       |                 |                  |<br>    Team A             Team B            Team C</pre><p>Initially everything is one application:</p><pre>frontend/<br>├── catalog/<br>├── cart/<br>├── checkout/<br>├── account/<br>├── search/<br>├── payments/<br>├── admin/<br>└── shared/</pre><p>That’s completely fine.</p><p>But eventually:</p><pre>Team A changes catalog<br>        ↓<br>CI runs entire frontend<br>        ↓<br>Team B&#39;s checkout tests fail<br>        ↓<br>Release blocked<br>        ↓<br>Team C changes shared component<br>        ↓<br>Everyone needs to upgrade<br>        ↓<br>Release train<br>        ↓<br>Coordination meeting<br>        ↓<br>😐</pre><p>The technical problem isn’t necessarily the size of the JavaScript bundle.</p><p>The real problem is <strong>coupling</strong>.</p><h3>3. Micro-Frontend Definition</h3><p>A practical definition is:</p><blockquote><em>A micro-frontend is an independently owned and deployable frontend application or domain that is composed into a larger user experience.</em></blockquote><p>The important words are:</p><h3>Independently owned</h3><p>A team owns it.</p><h3>Independently developed</h3><p>The team can develop without constantly coordinating with other teams.</p><h3>Independently deployed</h3><p>The team can release without rebuilding the entire application.</p><h3>Composable</h3><p>The user still experiences:</p><pre>ONE PRODUCT</pre><p>not:</p><pre>10 unrelated websites</pre><p>This distinction is extremely important.</p><h3>4. Micro-Frontend ≠ Microservice</h3><p>This is one of my favorite interview questions.</p><p>People often say:</p><blockquote><em>“Micro-frontends are microservices for the frontend.”</em></blockquote><p>That’s useful as an analogy, but technically incomplete.</p><p>Backend:</p><pre>               API Gateway<br>                     |<br>       +-------------+-------------+<br>       |             |             |<br>    Catalog       Payment       Orders<br>    Service       Service       Service</pre><p>Frontend:</p><pre>                   Browser<br>                     |<br>              Shell / Host<br>                     |<br>       +-------------+-------------+<br>       |             |             |<br>    Catalog        Cart         Checkout<br>       MFE           MFE           MFE</pre><p>But frontend composition has an additional problem:</p><p><strong>Everything must look and behave like one application.</strong></p><p>Backend services don’t have to share:</p><ul><li>CSS</li><li>browser history</li><li>DOM</li><li>JavaScript runtime</li><li>authentication UI</li><li>accessibility semantics</li><li>navigation</li><li>design system</li><li>browser storage</li></ul><p>Micro-frontends do.</p><p>That’s why frontend microservices can become surprisingly complicated.</p><h3>5. The First Architecture I Would Consider: Modular Monolith</h3><p>Before introducing micro-frontends, I’d probably try this:</p><pre>React Application<br><br>src/<br>├── domains/<br>│   ├── catalog/<br>│   ├── checkout/<br>│   ├── account/<br>│   └── payments/<br>│<br>├── shared/<br>│   ├── ui/<br>│   ├── auth/<br>│   └── analytics/<br>│<br>└── app/<br>    ├── router/<br>    └── bootstrap/</pre><p>Teams own boundaries:</p><pre>Catalog Team → catalog/<br>Checkout Team → checkout/<br>Account Team → account/</pre><p>But:</p><pre>           ONE BUILD<br>                 |<br>              ONE DEPLOY<br>                 |<br>              ONE APP</pre><p>This gives you:</p><ul><li>type safety</li><li>simple local development</li><li>simple debugging</li><li>easy shared state</li><li>easy routing</li><li>easy testing</li><li>no runtime federation problems</li></ul><p>And you may get <strong>80–90% of the organizational benefit</strong> without introducing runtime complexity.</p><p>This is why I would never answer an interview question with:</p><blockquote><em>“Large application = micro-frontends.”</em></blockquote><p>That’s a junior answer.</p><h3>6. When I Would Actually Introduce Micro-Frontends</h3><p>I start considering them when several of these are true:</p><h3>1. Multiple autonomous teams</h3><p>For example:</p><pre>Search Team<br>Catalog Team<br>Checkout Team<br>Payments Team<br>Account Team</pre><h3>2. Teams need independent releases</h3><p>For example:</p><pre>Catalog → deploy daily<br>Checkout → deploy twice a week<br>Payments → controlled release</pre><h3>3. Release coordination is hurting velocity</h3><p>If changing one area requires:</p><pre>5 teams<br>3 approvals<br>2 integration releases<br>1 regression cycle</pre><p>that’s a strong signal.</p><h3>4. Technology migration is required</h3><p>For example:</p><pre>AngularJS<br>   ↓<br>Angular<br>   ↓<br>React</pre><p>You may not be able to rewrite everything at once.</p><p>Micro-frontends can provide a <strong>strangler pattern</strong>.</p><h3>5. Different business domains have genuinely different ownership</h3><p>This is important.</p><p>I don’t split by technical convenience:</p><pre>Button MFE<br>Header MFE<br>Table MFE<br>Modal MFE</pre><p>I prefer business boundaries:</p><pre>Checkout MFE<br>Account MFE<br>Search MFE<br>Billing MFE</pre><h3>7. When I Would NOT Use Micro-Frontends</h3><p>This is just as important.</p><h3>Small team</h3><p>If four developers maintain the entire product:</p><pre>Team<br> ↓<br>One app<br> ↓<br>One deploy</pre><p>Micro-frontends are probably unnecessary.</p><h3>Early-stage startup</h3><p>You don’t know your domain boundaries yet.</p><p>Splitting too early can create permanent architecture around temporary assumptions.</p><h3>Everyone deploys together anyway</h3><p>This is a critical interview point.</p><p>If you have:</p><pre>Team A<br>Team B<br>Team C<br><br> ↓<br>Deploy every Friday</pre><p>then ask:</p><p><strong>What exactly are we gaining from independent deployment?</strong></p><p>If the answer is “nothing,” don’t introduce it.</p><h3>Performance is extremely sensitive</h3><p>Micro-frontends can introduce:</p><ul><li>additional JavaScript</li><li>additional network requests</li><li>duplicated dependencies</li><li>runtime loading</li><li>initialization overhead</li></ul><p>Module Federation can share dependencies, but dependency governance itself becomes a production concern. Webpack’s Module Federation model explicitly loads remote modules asynchronously at runtime. (<a href="https://webpack.js.org/concepts/module-federation/?utm_source=chatgpt.com">webpack</a>)</p><h3>8. The Three Major Composition Strategies</h3><p>There isn’t one micro-frontend architecture.</p><p>The major approaches are:</p><pre>1. Build-time integration<br>2. Runtime integration<br>3. Server-side composition</pre><p>And another boundary worth understanding:</p><pre>4. iframe isolation</pre><p>Let’s go through them.</p><h3>9. Build-Time Integration</h3><p>Imagine:</p><pre>Catalog package<br>Checkout package<br>Account package<br>       |<br>       ↓<br>   npm packages<br>       |<br>       ↓<br>    Host App<br>       |<br>       ↓<br>     Build</pre><p>For example:</p><pre>@company/catalog<br>@company/checkout<br>@company/account</pre><p>Host:</p><pre>import Catalog from &#39;@company/catalog&#39;;<br>import Checkout from &#39;@company/checkout&#39;;</pre><p>This gives you modular ownership.</p><p>But deployment isn’t truly independent.</p><p>If Catalog changes:</p><pre>Catalog<br>   ↓<br>publish package<br>   ↓<br>Host updates dependency<br>   ↓<br>Host rebuilds<br>   ↓<br>Host deploys</pre><p>So this is closer to a <strong>modular monolith</strong> than a true runtime micro-frontend architecture.</p><h3>10. Runtime Composition</h3><p>This is where Module Federation becomes interesting.</p><p>Conceptually:</p><pre>                Browser<br>                    |<br>                  Host<br>                    |<br>        +-----------+-----------+<br>        |           |           |<br>     Catalog      Cart       Checkout<br>      Remote      Remote       Remote</pre><p>The host can load remote code at runtime.</p><p>Webpack describes Module Federation as allowing multiple separate builds to form a single application, with builds exposing and consuming modules at runtime. (<a href="https://webpack.js.org/concepts/module-federation/?utm_source=chatgpt.com">webpack</a>)</p><p>Conceptually:</p><pre>const Checkout = lazy(<br>  () =&gt; import(&quot;checkout/Checkout&quot;)<br>);</pre><p>The host doesn’t necessarily contain Checkout at build time.</p><p>It can fetch it when needed.</p><h3>11. Module Federation Architecture</h3><p>Typical architecture:</p><pre>                    CDN<br>                     |<br>             remoteEntry.js<br>                     |<br>              +------+------+<br>              |             |<br>          Catalog MFE    Checkout MFE<br>              |             |<br>          catalog.js     checkout.js</pre><p>Host:</p><pre>Host Application<br>       |<br>       +----&gt; Catalog Remote<br>       |<br>       +----&gt; Checkout Remote<br>       |<br>       +----&gt; Account Remote</pre><p>This provides a very attractive property:</p><pre>Catalog team deploys<br>        ↓<br>Catalog remote changes<br>        ↓<br>Host does NOT necessarily rebuild</pre><p>That is the real value.</p><h3>12. But Here Comes the First Production Problem</h3><p>Imagine:</p><pre>Host<br>React 19<br><br>Remote A<br>React 19<br><br>Remote B<br>React 18</pre><p>Now you’re loading multiple versions of React into one runtime.</p><p>Things can go wrong.</p><p>And this gets even more interesting with:</p><pre>react<br>react-dom<br>router<br>state libraries<br>design system<br>i18n<br>analytics<br>date libraries</pre><p>You need a dependency-sharing strategy.</p><p>For example:</p><pre>React → singleton<br>ReactDOM → singleton<br>Design System → controlled version</pre><p>But now you have another problem:</p><p><strong>Who decides the version?</strong></p><p>That’s not a technical question anymore.</p><p>That’s governance.</p><p>A real production experience described in one public OneTrust architecture is instructive here: their Module Federation setup had roughly 50 remotes and dozens of teams, but shared dependency governance became a continuing coordination responsibility rather than a one-time configuration decision.</p><p>That’s exactly the kind of thing an architecture diagram doesn’t show.</p><h3>13. Single-SPA</h3><p>Another major approach is single-spa.</p><p>Instead of primarily solving:</p><blockquote><em>“How do I share modules?”</em></blockquote><p>single-spa focuses heavily on:</p><blockquote><em>“How do I orchestrate multiple frontend applications?”</em></blockquote><p>Conceptually:</p><pre>                Root Config<br>                     |<br>       +-------------+-------------+<br>       |             |             |<br>     React         Angular        Vue<br>      MFE           MFE           MFE</pre><p>The root decides:</p><pre>URL = /catalog<br>      ↓<br>Mount Catalog<br><br>URL = /checkout<br>      ↓<br>Unmount Catalog<br>      ↓<br>Mount Checkout</pre><p>The single-spa ecosystem has examples combining React, Angular, Vue and other frameworks in one application. (<a href="https://single-spa.js.org/docs/examples/?utm_source=chatgpt.com">Single SPA</a>)</p><h3>14. Module Federation vs Single-SPA</h3><p>This is a very common senior interview question.</p><p>Module Federationsingle-spaPrimary concernRuntime module sharingApplication orchestrationGranularityComponents/modulesApplications/routesFrameworkOften same ecosystemFramework agnosticRuntime loadingYesYesLifecycleLess opinionatedStrong lifecycle modelMigrationGoodExcellentMixed frameworksPossibleStrong use caseComponent sharingExcellentNot its primary purpose</p><p>A modern hybrid architecture can use both.</p><p>For example, a recent Vercel example combines single-spa for application lifecycle/routing with Module Federation for runtime component sharing.</p><h3>15. The Architecture I Often Prefer</h3><p>If we’re in a large enterprise:</p><pre>                     CDN<br>                      |<br>                Remote Manifest<br>                      |<br>                 Shell / Host<br>                      |<br>        +-------------+-------------+<br>        |             |             |<br>     Search         Catalog       Checkout<br>       MFE            MFE            MFE<br>        |              |              |<br>      React          React          React</pre><p>And underneath:</p><pre>                  Platform<br>                     |<br>       +-------------+-------------+<br>       |             |             |<br>     Auth          Design        Analytics<br>                   System</pre><p>The platform team owns the contracts.</p><p>Product teams own domains.</p><p>That’s the organizational architecture I’d want.</p><h3>16. The Most Important Design Principle: Domain Ownership</h3><p>Don’t do this:</p><pre>Header MFE<br>Footer MFE<br>Sidebar MFE<br>Button MFE<br>Modal MFE</pre><p>Now you have distributed UI spaghetti.</p><p>Instead:</p><pre>           Product<br>                |<br>     +----------+----------+<br>     |          |          |<br>  Catalog    Checkout    Account</pre><p>Each team owns a vertical slice.</p><p>For example:</p><pre>Checkout Team<br><br>UI<br> |<br>Checkout API<br> |<br>Payment API<br> |<br>Order API</pre><p>The frontend boundary should roughly follow the business boundary.</p><h3>17. Routing Is Harder Than It Looks</h3><p>Imagine:</p><pre>https://example.com/catalog<br>https://example.com/cart<br>https://example.com/checkout</pre><p>Who owns routing?</p><p>Possible answer:</p><pre>Shell owns top-level routes<br><br>/catalog     → Catalog MFE<br>/cart        → Cart MFE<br>/checkout    → Checkout MFE</pre><p>That is relatively clean.</p><p>But now:</p><pre>/checkout/payment<br>/checkout/review<br>/checkout/success</pre><p>Who owns those?</p><p>I usually prefer:</p><pre>Shell:<br> /checkout/* → Checkout MFE<br><br>Checkout:<br> /payment<br> /review<br> /success</pre><p>The shell owns the <strong>application boundary</strong>.</p><p>The MFE owns its internal navigation.</p><h3>18. Deep Linking</h3><p>Now consider:</p><pre>User opens:<br><br>/checkout/payment</pre><p>directly.</p><p>The system must:</p><ol><li>load shell</li><li>identify Checkout</li><li>load Checkout remote</li><li>restore authentication</li><li>initialize Checkout</li><li>restore route</li><li>load payment state</li><li>render page</li></ol><p>If any of those fail:</p><pre>Blank screen</pre><p>This is why production micro-frontends need serious error handling.</p><h3>19. What Happens When a Remote Is Down?</h3><p>This is one of the <strong>best interview questions</strong>.</p><p>Suppose:</p><pre>Host<br> |<br> +-- Catalog ✅<br> |<br> +-- Account ✅<br> |<br> +-- Checkout ❌</pre><p>Does the entire application die?</p><p>It shouldn’t.</p><p>You need failure isolation.</p><p>For example:</p><pre>Checkout failed<br><br>        ↓<br>Error Boundary<br>        ↓<br>&quot;Checkout is temporarily unavailable&quot;</pre><p>while:</p><pre>Catalog<br>Account<br>Search</pre><p>continue working.</p><p>This is one of the major architectural differences between a robust micro-frontend system and a demo.</p><h3>20. Runtime Failure Modes</h3><p>Real systems can fail because:</p><pre>Remote CDN unavailable<br>Remote returns 500<br>remoteEntry.js missing<br>DNS failure<br>CSP blocks script<br>CORS failure<br>Wrong version<br>Dependency conflict<br>React runtime mismatch<br>Broken remote deployment<br>Network timeout</pre><p>Therefore:</p><pre>Remote loading<br>      ↓<br>timeout<br>      ↓<br>retry<br>      ↓<br>fallback<br>      ↓<br>error boundary<br>      ↓<br>telemetry</pre><p>should be designed deliberately.</p><h3>21. Deployment Is a Distributed-System Problem</h3><p>This is one of the biggest lessons.</p><p>People think:</p><blockquote><em>“Frontend is frontend.”</em></blockquote><p>Once you introduce independent deployments, your frontend starts behaving like a distributed system.</p><p>Imagine:</p><pre>Host v10<br>Remote Checkout v17<br>Remote Catalog v23<br>Design System v42</pre><p>Now deploy:</p><pre>Checkout v18</pre><p>But Checkout expects:</p><pre>Design System v43</pre><p>while the host environment still provides:</p><pre>Design System v42</pre><p>Congratulations.</p><p>You’ve created a distributed compatibility problem.</p><h3>22. Contract Compatibility</h3><p>You need contracts.</p><p>For example:</p><pre>interface CheckoutContract {<br>  mount(container: HTMLElement, context: CheckoutContext): void;<br>}</pre><p>or with federated modules:</p><pre>export interface CheckoutProps {<br>  userId: string;<br>  cartId: string;<br>  currency: string;<br>}</pre><p>The contract must be backward compatible.</p><p>Think:</p><pre>Remote v2<br>       ↓<br>must work with<br>       ↓<br>Host v1</pre><p>at least during rollout.</p><h3>23. Never Assume Deployments Are Atomic</h3><p>In a monolith:</p><pre>Build<br> ↓<br>Test<br> ↓<br>Deploy</pre><p>Everything changes together.</p><p>Micro-frontends:</p><pre>Host v15<br>Remote A v10<br>Remote B v21<br>Remote C v7</pre><p>These versions coexist.</p><p>That means you need:</p><ul><li>compatibility policies</li><li>rollback</li><li>versioning</li><li>health checks</li><li>canary deployments</li><li>observability</li></ul><p>This is one reason micro-frontends require platform engineering maturity.</p><h3>24. Blue-Green / Canary Deployment</h3><p>For a remote:</p><pre>Checkout v17 → 95%<br>Checkout v18 → 5%</pre><p>Monitor:</p><pre>JS errors<br>load failures<br>checkout conversion<br>latency<br>API errors</pre><p>If bad:</p><pre>v18 → 0%<br>v17 → 100%</pre><p>This becomes much more powerful than simply deploying JavaScript.</p><h3>25. Shared State: The Most Dangerous Rabbit Hole</h3><p>Suppose:</p><pre>Header<br>Cart<br>Checkout<br>Account</pre><p>all need:</p><pre>currentUser<br>cart<br>locale<br>currency<br>featureFlags</pre><p>A junior solution is:</p><blockquote><em>“Let’s create one global Redux store.”</em></blockquote><p>And suddenly you’ve built:</p><pre>               Global Store<br>                      |<br>        +-------------+-------------+<br>        |             |             |<br>      Cart         Checkout       Account</pre><p>Now your micro-frontends are deeply coupled again.</p><p>You’ve effectively created a <strong>distributed monolith</strong>.</p><h3>26. Prefer Local State</h3><p>For example:</p><pre>Catalog MFE<br><br>catalogFilters<br>selectedProduct<br>pagination</pre><p>belongs locally.</p><p>Checkout:</p><pre>paymentMethod<br>shippingAddress<br>coupon</pre><p>belongs locally.</p><p>Only truly cross-domain state should cross boundaries.</p><h3>27. What State Should Be Shared?</h3><p>Usually:</p><pre>Authentication identity<br>Locale<br>Theme<br>Feature flags<br>Maybe cart identifier</pre><p>But even these should have controlled APIs.</p><p>For example:</p><pre>platform.auth.getCurrentUser()</pre><p>rather than:</p><pre>window.globalRedux.store.user</pre><p>The second creates tight coupling.</p><h3>28. Event-Based Communication</h3><p>Sometimes events are appropriate.</p><p>Example:</p><pre>Cart MFE<br><br>dispatch:<br>cart:updated</pre><p>Checkout listens:</p><pre>window.addEventListener(<br>  &quot;cart:updated&quot;,<br>  handler<br>)</pre><p>Conceptually:</p><pre>Cart<br> |<br> | cart:updated<br> ↓<br>Event Bus<br> |<br> +----&gt; Header<br> |<br> +----&gt; Checkout<br> |<br> +----&gt; Analytics</pre><p>But don’t turn your application into:</p><pre>event1<br>event2<br>event3<br>event4<br>...<br>event237</pre><p>Otherwise debugging becomes painful.</p><h3>29. Better Event Design</h3><p>Events should represent <strong>business facts</strong>.</p><p>Good:</p><pre>cart.updated<br>user.logged_in<br>order.completed<br>payment.failed</pre><p>Bad:</p><pre>button.clicked<br>component.rendered<br>modal.opened<br>setStateCalled</pre><p>Business events survive UI refactoring.</p><p>Component events don’t.</p><h3>30. Authentication</h3><p>Another interview favorite.</p><p>Question:</p><blockquote><em>“How would you implement authentication across micro-frontends?”</em></blockquote><p>I don’t want each MFE doing:</p><pre>Login independently<br>Refresh token independently<br>Store auth independently</pre><p>Instead:</p><pre>                   Identity Provider<br>                         |<br>                      Shell<br>                         |<br>              Auth Platform Contract<br>                         |<br>        +----------------+----------------+<br>        |                |                |<br>      Catalog          Cart            Checkout</pre><p>The platform can expose:</p><pre>auth.getUser()<br>auth.getAccessToken()<br>auth.logout()</pre><p>The exact implementation depends on your identity architecture.</p><h3>31. Security</h3><p>Runtime JavaScript composition introduces serious trust questions.</p><p>If you allow:</p><pre>https://remote-a.company.com</pre><p>to execute JavaScript in your application context, you are effectively trusting that deployment.</p><p>If the remote is compromised:</p><pre>Remote<br>  ↓<br>JavaScript<br>  ↓<br>Browser context<br>  ↓<br>Potential access to application capabilities</pre><p>This is fundamentally different from an iframe.</p><h3>32. iframe vs JavaScript Micro-Frontend</h3><p>An iframe provides stronger isolation:</p><pre>Host<br> |<br> +---- iframe ----+<br> |                |<br> |   MFE          |<br> |                |<br> +----------------+</pre><p>The iframe has:</p><ul><li>separate JS context</li><li>separate DOM</li><li>stronger isolation</li></ul><p>But communication becomes:</p><pre>postMessage()</pre><p>and UX integration is harder.</p><p>For highly isolated applications, iframes can actually be a reasonable architectural decision.</p><p>For example:</p><pre>Main banking app<br>        |<br>        +---- third-party KYC widget</pre><p>Isolation may be more valuable than seamless integration.</p><h3>33. CSS Is One of the Most Underestimated Problems</h3><p>Imagine:</p><pre>Catalog MFE:<br><br>.button {<br>  padding: 20px;<br>}</pre><p>Checkout:</p><pre>.button {<br>  padding: 5px;<br>}</pre><p>Welcome to CSS collisions.</p><p>Possible strategies:</p><h3>CSS Modules</h3><pre>Catalog_button_x83d<br>Checkout_button_91aa</pre><h3>Naming conventions</h3><pre>catalog-button<br>checkout-button</pre><h3>Shadow DOM</h3><pre>&lt;catalog-component&gt;<br>   #shadow-root<br>      ...<br>&lt;/catalog-component&gt;</pre><h3>Design system</h3><p>The best long-term strategy is usually some combination of:</p><pre>shared design system<br>+<br>strong style isolation</pre><h3>34. Design System Governance</h3><p>This is another place where teams can accidentally destroy the benefits of micro-frontends.</p><p>Imagine:</p><pre>Team A → Button v1<br>Team B → Button v7<br>Team C → Button v12<br>Team D → custom button</pre><p>Your product becomes visually inconsistent.</p><p>So I typically establish:</p><pre>Platform Team<br>     |<br>Design System<br>     |<br>+----+----+----+<br>|    |    |    |<br>A    B    C    D</pre><p>But importantly:</p><p><strong>The design system should not become a giant shared application.</strong></p><p>Prefer stable primitives and versioned contracts.</p><h3>35. Performance</h3><p>This is where the “micro” in micro-frontends can become funny.</p><p>Suppose every MFE ships:</p><pre>React<br>React Router<br>lodash<br>analytics<br>design system</pre><p>You might accidentally download:</p><pre>React × 5<br>Router × 4<br>Analytics × 5</pre><p>The architecture diagram looks beautiful.</p><p>The Lighthouse score looks terrible.</p><h3>36. Performance Strategy</h3><p>I would consider:</p><h3>Dependency sharing</h3><p>Use federation/shared dependencies where appropriate.</p><h3>Route-level loading</h3><p>Don’t load Checkout on /catalog.</p><pre>/catalog<br>  ↓<br>Catalog only</pre><h3>Prefetching</h3><p>When the user approaches checkout:</p><pre>Cart<br> ↓<br>prefetch Checkout</pre><h3>CDN</h3><p>Remotes should generally be aggressively cached.</p><h3>Chunking</h3><p>Avoid one huge remote bundle.</p><h3>Performance budgets</h3><p>Each team gets budgets:</p><pre>Initial JS &lt; X KB<br>Remote load &lt; Y ms</pre><p>Now performance becomes an organizational responsibility.</p><h3>37. The Browser Network Becomes Part of Your Architecture</h3><p>Monolith:</p><pre>HTML<br> ↓<br>main.js<br> ↓<br>app</pre><p>Micro-frontends:</p><pre>HTML<br> ↓<br>Shell<br> ↓<br>remote manifest<br> ↓<br>remoteEntry<br> ↓<br>chunks<br> ↓<br>dependencies<br> ↓<br>API</pre><p>You now have more network failure points.</p><p>That’s why caching strategy becomes critical.</p><h3>38. CDN Strategy</h3><p>A remote can be published:</p><pre>cdn.company.com/<br>   checkout/<br>      v17/<br>      v18/<br>      v19/</pre><p>Then a manifest might point to:</p><pre>{<br>  &quot;checkout&quot;: &quot;https://cdn.company.com/checkout/v19/remoteEntry.js&quot;<br>}</pre><p>Now rollback can be:</p><pre>manifest<br>checkout → v18</pre><p>rather than rebuilding the entire application.</p><p>This is a very powerful operational pattern.</p><h3>39. But Never Delete Versions Immediately</h3><p>Imagine:</p><pre>User opens app<br> ↓<br>Host loads v18</pre><p>Then you deploy v19.</p><p>If you immediately delete v18:</p><pre>User navigates<br> ↓<br>v18 chunk requested<br> ↓<br>404</pre><p>So old remote versions often need a retention period.</p><p>This is exactly the kind of production issue that isn’t obvious from tutorials.</p><h3>40. Observability</h3><p>With a monolith:</p><pre>Error:<br>Checkout failed</pre><p>With micro-frontends:</p><pre>Which remote?<br>Which version?<br>Which host version?<br>Which browser?<br>Which CDN?<br>Which dependency?<br>Which deployment?</pre><p>You need metadata.</p><p>For example:</p><pre>application: checkout<br>version: 19.4.2<br>hostVersion: 8.7.1<br>environment: production</pre><p>Attach this to:</p><ul><li>logs</li><li>error tracking</li><li>tracing</li><li>metrics</li></ul><p>Then:</p><pre>Checkout errors increased<br>        ↓<br>version = 19.4.2<br>        ↓<br>deployment happened 12 minutes ago</pre><p>That’s actionable.</p><h3>41. Real-Time Monitoring</h3><p>For critical flows, I’d monitor:</p><pre>Remote load success rate<br>Remote load latency<br>JS exception rate<br>API failure rate<br>Error boundary activation<br>Navigation failures<br>Conversion rate</pre><p>Example:</p><pre>checkout remote load success<br>99.98% → 98.2%</pre><p>That should trigger an alert.</p><p>Not because JavaScript failed.</p><p>Because <strong>the business flow is failing</strong>.</p><h3>42. Real-World Example: Zalando</h3><p>Zalando is one of the useful real-world examples to study.</p><p>Their engineering organization described Project Mosaic, where frontend fragments were owned by different teams and composed into the larger site. The architecture helped teams work independently at scale, while later iterations addressed limitations of the fragment approach. (<a href="https://engineering.zalando.com/posts/2021/03/micro-frontends-part1.html?utm_source=chatgpt.com">engineering.zalando.com</a>)</p><p>The lesson isn’t:</p><blockquote><em>“Use Mosaic.”</em></blockquote><p>The lesson is:</p><blockquote><strong><em>At large organizational scale, independent ownership becomes a first-class architectural concern.</em></strong></blockquote><h3>43. Real-World Example: OneTrust</h3><p>A particularly useful engineering case study describes OneTrust evolving through several frontend architectures:</p><pre>Per-product SPAs<br>       ↓<br>Angular Elements host<br>       ↓<br>Manifest-based loading<br>       ↓<br>Module Federation<br>       ↓<br>~50 remotes</pre><p>The interesting part isn’t the technology.</p><p>It’s the organizational outcome:</p><pre>Dozens of teams<br>        ↓<br>Independent remotes<br>        ↓<br>Independent deployment cadence<br>        ↓<br>Shared platform contracts</pre><p>But the case study also highlights the ongoing cost: shared dependency governance remained a continuous coordination problem. (<a href="https://www.dhruvaldarji.com/projects/micro-frontend-architecture/?utm_source=chatgpt.com">Dhruval Darji</a>)</p><p>That’s exactly what experienced engineers should recognize.</p><h3>44. Real-World Example: A Large E-Commerce Platform</h3><p>Let’s design one.</p><pre>                          Shell<br>                           |<br>       +-------------------+-------------------+<br>       |                   |                   |<br>    Catalog              Search             Account<br>       |                   |                   |<br>       +-------------------+-------------------+<br>                           |<br>                         Cart<br>                           |<br>                       Checkout<br>                           |<br>                        Payment</pre><p>Teams:</p><pre>Catalog Team<br>Search Team<br>Account Team<br>Checkout Team<br>Payments Team</pre><p>Deployment:</p><pre>catalog.company.com<br>search.company.com<br>checkout.company.com</pre><p>But user sees:</p><pre>ONE WEBSITE</pre><p>This is a good micro-frontend candidate.</p><h3>45. What If Checkout Needs Cart Data?</h3><p>Don’t share the entire Redux store.</p><p>Instead:</p><pre>checkout.mount({<br>  cartId,<br>  userId<br>});</pre><p>or:</p><pre>Cart publishes:<br>cart.updated<br><br>Checkout consumes:<br>cart.updated</pre><p>The contract is small.</p><p>That keeps ownership clean.</p><h3>46. What If Checkout Needs Product Data?</h3><p>I wouldn’t make:</p><pre>Checkout → Catalog internal state</pre><p>Instead:</p><pre>Checkout<br>   |<br>   ↓<br>Backend API / BFF<br>   |<br>   ↓<br>Product data</pre><p>Each domain should ideally own its backend contracts too.</p><p>This avoids:</p><pre>Checkout frontend<br>      ↓<br>Catalog frontend internal implementation</pre><p>which is dangerous coupling.</p><h3>47. Backend-for-Frontend Can Help</h3><p>You may have:</p><pre>Catalog MFE<br>      |<br>Catalog BFF<br>      |<br>Catalog Services</pre><p>and:</p><pre>Checkout MFE<br>      |<br>Checkout BFF<br>      |<br>Checkout Services</pre><p>Now the frontend boundary aligns with the backend/domain boundary.</p><p>This can be a very powerful architecture.</p><h3>48. Testing Micro-Frontends</h3><p>You need several levels.</p><h3>Unit tests</h3><p>Each team owns:</p><pre>components<br>business logic<br>hooks<br>utilities</pre><h3>MFE integration tests</h3><p>Test:</p><pre>Checkout MFE<br>+<br>its contracts</pre><h3>Contract tests</h3><p>Verify:</p><pre>Host ↔ Remote</pre><h3>End-to-end tests</h3><p>Verify:</p><pre>Catalog → Cart → Checkout</pre><p>But don’t create one gigantic E2E suite for everything.</p><p>Otherwise independent teams are back to waiting on one giant pipeline.</p><h3>49. Contract Testing Is Extremely Valuable</h3><p>Suppose Host expects:</p><pre>CheckoutProps {<br>  cartId: string;<br>}</pre><p>Checkout changes it to:</p><pre>CheckoutProps {<br>  cart: Cart;<br>}</pre><p>The remote works perfectly in isolation.</p><p>But production breaks.</p><p>Contract testing catches:</p><pre>Host contract<br>       ↕<br>Remote contract</pre><p>before deployment.</p><h3>50. Local Development Is Another Pain Point</h3><p>A junior architecture diagram:</p><pre>Host<br> ↓<br>MFE A<br> ↓<br>MFE B<br> ↓<br>MFE C</pre><p>looks great.</p><p>Then a developer says:</p><blockquote><em>“I need to run six applications locally before I can work.”</em></blockquote><p>😐</p><p>That’s a real productivity problem.</p><h3>51. Local Development Strategy</h3><p>Provide:</p><pre>host<br> ↓<br>mock remote</pre><p>when working on Host.</p><p>Or:</p><pre>Host<br> ↓<br>local Catalog<br> ↓<br>remote Checkout<br> ↓<br>remote Account</pre><p>Only the service being changed needs to run locally.</p><p>This dramatically improves developer experience.</p><h3>52. Versioned Local Manifests</h3><p>For example:</p><pre>.env.local<br><br>CATALOG_REMOTE=localhost<br>CHECKOUT_REMOTE=staging<br>ACCOUNT_REMOTE=staging</pre><p>Then developers can mix:</p><pre>local<br>+<br>staging<br>+<br>production-like</pre><p>remotes.</p><p>This is extremely useful.</p><h3>53. CI/CD</h3><p>Each MFE should ideally have:</p><pre>checkout/<br>  test<br>  build<br>  security scan<br>  publish<br>  deploy</pre><p>independent from:</p><pre>catalog/<br>search/<br>account/</pre><p>But there should also be an integration pipeline:</p><pre>Host<br>+<br>all critical remotes<br>       ↓<br>Smoke tests<br>       ↓<br>Production</pre><p>Otherwise independent deployment becomes independent breakage.</p><h3>54. The “Distributed Monolith” Problem</h3><p>This is probably the biggest failure mode.</p><p>You start with:</p><pre>Monolith</pre><p>Split it:</p><pre>MFE A<br>MFE B<br>MFE C</pre><p>But they still require:</p><pre>same release<br>same state<br>same dependencies<br>same deployment<br>same team<br>same architecture</pre><p>You’ve achieved:</p><blockquote><strong><em>All the complexity of micro-frontends without the benefit of independence.</em></strong></blockquote><p>That’s a distributed monolith.</p><h3>55. Warning Signs of a Distributed Monolith</h3><p>If you hear:</p><blockquote><em>“We can’t deploy Checkout without Catalog.”</em></blockquote><p>Red flag.</p><blockquote><em>“All MFEs must upgrade React together.”</em></blockquote><p>Potential red flag.</p><blockquote><em>“Everyone uses the same global store.”</em></blockquote><p>Red flag.</p><blockquote><em>“Every change requires modifying the shell.”</em></blockquote><p>Red flag.</p><blockquote><em>“The shell knows all internal details of every MFE.”</em></blockquote><p>Red flag.</p><blockquote><em>“We release everything every Friday.”</em></blockquote><p>Huge red flag.</p><h3>56. Shell Should Be Boring</h3><p>This is a principle I strongly recommend.</p><p>The shell should primarily handle:</p><pre>routing<br>authentication<br>layout<br>navigation<br>global platform capabilities<br>loading/error boundaries<br>observability</pre><p>Not:</p><pre>catalog business logic<br>checkout business logic<br>payment logic<br>account business logic</pre><p>Think:</p><pre>Shell = platform</pre><pre>MFE = product domain</pre><h3>57. Shell Should Not Become the New Monolith</h3><p>A common evolution is:</p><pre>Old Monolith<br>     ↓<br>Micro-frontends<br>     ↓<br>Huge Shell<br>     ↓<br>🤦</pre><p>Everything moves into the shell:</p><pre>routing<br>state<br>business logic<br>API calls<br>analytics<br>feature flags<br>UI<br>permissions</pre><p>Then every MFE depends on it.</p><p>You’ve simply moved the monolith.</p><h3>58. Shared Libraries Need Governance</h3><p>Some things should be shared:</p><pre>TypeScript config<br>ESLint<br>Design system<br>Authentication SDK<br>Analytics SDK<br>Testing utilities</pre><p>Some things should not:</p><pre>Checkout internal state<br>Catalog internal components<br>Payment implementation<br>Domain-specific hooks</pre><p>A good rule:</p><blockquote><strong><em>Share capabilities, not business ownership.</em></strong></blockquote><h3>59. Technology Diversity: Be Careful</h3><p>One argument for micro-frontends is:</p><pre>Team A → React<br>Team B → Vue<br>Team C → Angular</pre><p>Technically possible.</p><p>But should you?</p><p>Usually, I’d ask:</p><blockquote><em>Why?</em></blockquote><p>If the answer is:</p><blockquote><em>“Because teams like different frameworks.”</em></blockquote><p>That’s not a strong reason.</p><p>If the answer is:</p><blockquote><em>“We’re migrating AngularJS to React over three years.”</em></blockquote><p>Now it’s compelling.</p><p>Technology diversity should be a <strong>constraint you accommodate</strong>, not a goal you pursue.</p><h3>60. Migration Strategy: Strangler Pattern</h3><p>Suppose you have:</p><pre>Old AngularJS application</pre><p>You can’t rewrite it.</p><p>Instead:</p><pre>                  Shell<br>                    |<br>        +-----------+-----------+<br>        |                       |<br>   Legacy AngularJS         New React<br>        |                       |<br>    old routes             new routes</pre><p>Gradually:</p><pre>AngularJS<br> ↓<br>AngularJS + React<br> ↓<br>Mostly React<br> ↓<br>React</pre><p>This is one of the strongest real-world use cases for micro-frontends.</p><h3>61. What About SEO?</h3><p>This matters for:</p><ul><li>e-commerce</li><li>content</li><li>marketing</li><li>public pages</li></ul><p>Client-side runtime composition can complicate:</p><pre>SEO<br>TTFB<br>initial rendering<br>crawlability</pre><p>For public content, server-side composition or SSR may be preferable.</p><p>You need to ask:</p><blockquote><em>Does this page need to be indexable?</em></blockquote><p>If yes, architecture changes.</p><h3>62. Server-Side Composition</h3><p>Instead of:</p><pre>Browser<br> ↓<br>load all MFEs</pre><p>you can compose HTML on the server:</p><pre>Request<br>   ↓<br>Edge / Server<br>   |<br>   +-- Catalog fragment<br>   +-- Search fragment<br>   +-- Account fragment<br>   |<br>   ↓<br>HTML<br>   ↓<br>Browser</pre><p>This can improve initial rendering characteristics.</p><p>But now the server becomes part of the composition infrastructure.</p><p>Again:</p><p><strong>There is no free lunch.</strong></p><h3>63. Runtime Composition vs Server Composition</h3><p>RequirementRuntimeServerIndependent deploymentExcellentExcellentSPA UXExcellentGoodInitial renderingCan be harderStrongSEOMore workStrongBrowser complexityHigherLowerRuntime failuresMore visibleDifferent failure modelDynamic UIExcellentGood</p><p>Choose based on requirements, not fashion.</p><h3>64. What I Would Architect for a 100-Engineer Frontend</h3><p>Suppose:</p><pre>100 engineers<br>12 teams<br>10 business domains</pre><p>I’d probably build:</p><pre>                      CDN / Edge<br>                         |<br>                       Shell<br>                         |<br>       +-----------------+------------------+<br>       |                 |                  |<br>    Catalog            Search             Account<br>       |                 |                  |<br>    Checkout           Orders             Billing<br>       |                 |                  |<br>       +-----------------+------------------+<br>                         |<br>                    Platform APIs<br>                         |<br>        +----------------+----------------+<br>        |                |                |<br>       Auth           Analytics       Feature Flags</pre><p>With:</p><pre>Module Federation<br>+<br>strong contracts<br>+<br>shared design system<br>+<br>independent CI/CD<br>+<br>observability<br>+<br>canary deployments</pre><p>If teams use different frameworks during migration:</p><pre>single-spa<br>+<br>Module Federation where appropriate</pre><h3>65. My Decision Matrix</h3><p>Here’s how I’d answer an architecture review.</p><p>SituationRecommendation5 engineersMonolith10 engineersModular monolith20 engineersModular monolith first50 engineersDepends on team boundaries100+ engineersConsider MFEsIndependent releases requiredStrong MFE candidateLegacy migrationStrong MFE candidateMultiple acquisitions/productsStrong candidateSmall startupUsually noOne teamUsually noPerformance-critical SPABe cautiousMixed frameworks for migrationsingle-spa/MFESame React stackModule FederationStrong isolation requirementiframeMostly content/SEOServer composition</p><p>The number of engineers isn’t a rule.</p><p>The <strong>coordination cost</strong> is the real metric.</p><h3>66. The Interview Question: “Why Not Just Use Monorepo?”</h3><p>This is an excellent question.</p><p>My answer:</p><blockquote><em>A monorepo solves code organization and collaboration problems. It doesn’t automatically solve independent deployment.</em></blockquote><p>For example:</p><pre>Monorepo<br><br>Catalog<br>Checkout<br>Account<br>   ↓<br>ONE BUILD<br>ONE DEPLOY</pre><p>Micro-frontends:</p><pre>Catalog → deploy independently<br>Checkout → deploy independently<br>Account → deploy independently</pre><p>If independent deployment isn’t required, the monorepo may be the better solution.</p><h3>67. Interview Question: “Why Not Just Use npm Packages?”</h3><p>Answer:</p><p>npm packages provide:</p><pre>reuse<br>versioning<br>ownership</pre><p>but normally require:</p><pre>publish<br> ↓<br>upgrade dependency<br> ↓<br>rebuild host<br> ↓<br>deploy host</pre><p>Module Federation can provide:</p><pre>runtime composition<br>+<br>independent deployment</pre><p>That’s the distinction.</p><h3>68. Interview Question: “How Do You Share State?”</h3><p>Strong answer:</p><blockquote><em>I avoid sharing state by default. I keep domain state local and expose a small platform contract for cross-cutting concerns such as authentication, locale and feature flags. When domains need to communicate, I prefer explicit business events or APIs over a shared global store.</em></blockquote><p>That’s much better than:</p><blockquote><em>“We use Redux.”</em></blockquote><h3>69. Interview Question: “How Do You Handle Remote Failure?”</h3><p>I’d answer:</p><pre>Remote loader<br>    ↓<br>timeout<br>    ↓<br>retry<br>    ↓<br>error boundary<br>    ↓<br>fallback UI<br>    ↓<br>telemetry</pre><p>And importantly:</p><blockquote><em>A failed Checkout MFE should not necessarily crash Catalog.</em></blockquote><p>That’s the essence of failure isolation.</p><h3>70. Interview Question: “How Do You Prevent Version Conflicts?”</h3><p>I’d discuss:</p><pre>dependency sharing<br>version ranges<br>singleton dependencies<br>compatibility testing<br>lock/version policies<br>contract tests<br>canary releases<br>rollback</pre><p>And then mention:</p><blockquote><em>The difficult part isn’t technically configuring shared dependencies. The difficult part is governance across teams.</em></blockquote><p>That answer sounds much more experienced.</p><h3>71. Interview Question: “How Would You Roll Back One MFE?”</h3><p>Answer:</p><pre>CDN<br> |<br> +-- checkout/v17<br> +-- checkout/v18<br> +-- checkout/v19</pre><p>Manifest:</p><pre>{<br>  &quot;checkout&quot;: &quot;v19&quot;<br>}</pre><p>Rollback:</p><pre>checkout → v18</pre><p>Then verify:</p><pre>load success<br>JS errors<br>business metrics</pre><p>No need to rebuild the entire platform.</p><h3>72. Interview Question: “How Do You Debug Production?”</h3><p>I’d want every error to contain:</p><pre>hostVersion<br>remoteName<br>remoteVersion<br>browser<br>user/session correlation ID<br>route<br>deployment ID</pre><p>Then:</p><pre>Error spike<br>   ↓<br>checkout v19.2<br>   ↓<br>deployed 10 minutes ago<br>   ↓<br>rollback</pre><p>Without version metadata, debugging becomes painful.</p><h3>73. Interview Question: “What Is the Biggest Problem With Micro-Frontends?”</h3><p>My answer:</p><blockquote><strong><em>They move complexity from compile time into runtime and organizational coordination.</em></strong></blockquote><p>Monolith:</p><pre>Complexity<br>   ↓<br>build/release</pre><p>Micro-frontends:</p><pre>Complexity<br>   ↓<br>runtime<br>+<br>deployment<br>+<br>contracts<br>+<br>dependency management<br>+<br>observability<br>+<br>team governance</pre><p>That’s the trade-off.</p><h3>74. The Most Important Trade-Off</h3><p>Micro-frontends give you:</p><pre>BENEFITS<br><br>Independent deployment<br>Team autonomy<br>Domain ownership<br>Gradual migration<br>Technology flexibility<br>Smaller team-owned codebases</pre><p>But cost:</p><pre>COST<br><br>Runtime complexity<br>Network overhead<br>Dependency conflicts<br>CSS conflicts<br>State coordination<br>Testing complexity<br>Observability complexity<br>Deployment compatibility<br>Local development complexity<br>Governance</pre><p>The architecture makes sense only if:</p><pre>Value of independence<br>        &gt;<br>Cost of distributed frontend</pre><h3>75. A Simple Decision Formula</h3><p>I often think about it like this:</p><pre>Micro-Frontend Value<br>=<br>Coordination Cost<br>+<br>Deployment Cost<br>+<br>Migration Value<br>+<br>Team Autonomy<br><br>minus<br>Runtime Complexity<br>+<br>Operational Cost<br>+<br>Performance Cost<br>+<br>Governance Cost</pre><p>If the result isn’t clearly positive:</p><p><strong>don’t do it.</strong></p><h3>76. My “10+ Years Experience” Rule</h3><p>If someone asks me:</p><blockquote><em>“Should we use micro-frontends?”</em></blockquote><p>I don’t start with:</p><pre>Webpack<br>Module Federation<br>single-spa</pre><p>I start with:</p><pre>How many teams?<br><br>Who owns what?<br>How frequently do they deploy?<br>What prevents independent deployment today?<br>Are boundaries stable?<br>Do teams need different technology?<br>How important is performance?<br>How important is SEO?<br>How much platform engineering do we have?</pre><p>Only after answering those questions do I choose the technology.</p><h3>77. The Architecture I Would Avoid</h3><pre>                  Giant Shell<br>                      |<br>       +--------------+--------------+<br>       |              |              |<br>      MFE            MFE            MFE<br>       |              |              |<br>       +--------------+--------------+<br>                      |<br>                 Global Redux<br>                      |<br>                 Shared Utils<br>                      |<br>               Shared Components<br>                      |<br>               Shared API Layer</pre><p>Why?</p><p>Because now:</p><pre>MFE A depends on B<br>MFE B depends on C<br>C depends on global state<br>global state depends on shell<br>shell depends on all MFEs</pre><p>You’ve created a dependency graph:</p><pre>A ←→ B<br>       ↕   ↕<br>       C ←→ D<br>        ↕<br>       Shell</pre><p>That’s not independent architecture.</p><h3>78. The Architecture I Want</h3><pre>                     SHELL<br>                       |<br>        +--------------+--------------+<br>        |              |              |<br>    Catalog         Checkout        Account<br>      Team             Team           Team<br>        |               |              |<br>   local state      local state    local state<br>        |               |              |<br>     API/BFF          API/BFF        API/BFF</pre><pre>          Shared Platform Capabilities<br>                     |<br>        +------------+------------+<br>        |            |            |<br>       Auth       Analytics     Design System</pre><p>Dependencies should mostly point:</p><pre>Domain<br>  ↓<br>Platform capability</pre><p>not:</p><pre>Domain A<br>  ↓<br>Domain B<br>  ↓<br>Domain C</pre><h3>79. The One-Sentence Interview Answer</h3><p>If the interviewer asks:</p><blockquote><strong><em>“Explain micro-frontends.”</em></strong></blockquote><p>I’d say:</p><blockquote><em>“Micro-frontends are an architectural approach where independently owned frontend domains can be developed, tested and deployed independently and then composed into a single user experience. I don’t introduce them simply because an application is large; I introduce them when organizational boundaries and independent deployment requirements justify the runtime and operational complexity.”</em></blockquote><p>That’s a strong senior-level answer.</p><h3>80. Final Mental Model</h3><p>Don’t think:</p><pre>Micro-frontend<br>=<br>Webpack Module Federation</pre><p>Think:</p><pre>                    BUSINESS DOMAINS<br>                          |<br>                   TEAM OWNERSHIP<br>                          |<br>                 INDEPENDENT DELIVERY<br>                          |<br>                CONTRACT-BASED COMPOSITION<br>                          |<br>          +---------------+---------------+<br>          |               |               |<br>       Runtime         Server          iframe<br>      Federation     Composition      Isolation<br>          |<br>    Module Federation<br>       / single-spa</pre><p>The technology is the <strong>implementation detail</strong>.</p><p>The architecture is about:</p><blockquote><strong><em>Who owns what, who can change what, and who can deploy what without asking everyone else for permission?</em></strong></blockquote><p>That’s the real reason micro-frontends exist.</p><p>And that’s also why, after years of frontend architecture work, my default answer isn’t <strong>“yes, use micro-frontends.”</strong></p><p>It’s:</p><blockquote><strong><em>First prove that independent ownership and deployment are worth paying for. Then choose the smallest architecture that gives you that independence.</em></strong></blockquote><h3>A practical stack I’d consider in 2026</h3><p>For a large React organization:</p><pre>                   CDN / Edge<br>                        |<br>                 Shell / Host<br>                        |<br>            Module Federation<br>                        |<br>       +----------------+----------------+<br>       |                |                |<br>    Catalog          Checkout          Account<br>       |                |                |<br>     React            React            React<br>       |                |                |<br>       +----------------+----------------+<br>                        |<br>                Shared Platform APIs<br>                        |<br>        +---------------+---------------+<br>        |               |               |<br>       Auth        Feature Flags    Analytics<br><br><br>Infrastructure:<br>-----------------------------------------<br>CI/CD<br>Canary deployment<br>Contract testing<br>Error boundaries<br>Observability<br>Versioned remotes<br>CDN caching<br>Design system<br>Performance budgets</pre><p>If you’re migrating a large Angular/AngularJS estate:</p><pre>Shell<br>  |<br>single-spa<br>  |<br>+---------+---------+---------+<br>|         |         |         |<br>AngularJS Angular   React    Vue<br>              |<br>        Module Federation</pre><p>And if you don’t have a strong reason for any of this:</p><pre>Modular Monolith<br>              ↓<br>        simpler system<br>              ↓<br>        happier engineers</pre><p>That last option is underrated.</p><p>For reference, Webpack’s official Module Federation documentation explains the runtime remote model, while single-spa’s documentation provides multi-framework examples; both are useful when moving from architecture concepts into implementation. (<a href="https://webpack.js.org/concepts/module-federation/?utm_source=chatgpt.com">webpack</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45d4e340562a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend Testing Strategy for Enterprise Applications]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/frontend-testing-strategy-for-enterprise-applications-10402d870e5f?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/10402d870e5f</guid>
            <category><![CDATA[frontend-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[testing-strategies]]></category>
            <category><![CDATA[frontend-arch]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 13:38:36 GMT</pubDate>
            <atom:updated>2026-08-31T13:38:36.804Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>From Unit Tests to Production Confidence — A 10+ Year Frontend Engineering Perspective</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsaRy7VgHt26jJBFtmfhfg.png" /></figure><h3>Introduction</h3><p>After more than a decade of working on frontend applications, one thing becomes clear:</p><blockquote><strong><em>Testing is not about writing more tests. It’s about creating confidence with the right tests at the right boundaries.</em></strong></blockquote><p>I’ve seen both extremes.</p><p>One team had thousands of unit tests, yet production bugs were common.</p><p>Another team had very few unit tests but a carefully designed integration and E2E suite, and releases were significantly more predictable.</p><p>The problem wasn’t the number of tests.</p><p>The problem was <strong>the testing strategy</strong>.</p><p>In a small application, you can get away with:</p><pre>Component<br>   ↓<br>Unit Test</pre><p>But enterprise applications look more like:</p><pre>                    ┌─────────────────────────┐<br>                    │        Users            │<br>                    └────────────┬────────────┘<br>                                 │<br>                                 ▼<br>                    ┌─────────────────────────┐<br>                    │      Web Application     │<br>                    │    React / Next.js       │<br>                    └────────────┬────────────┘<br>                                 │<br>              ┌──────────────────┼──────────────────┐<br>              │                  │                  │<br>              ▼                  ▼                  ▼<br>        ┌───────────┐      ┌───────────┐      ┌───────────┐<br>        │ Components│      │   State   │      │   Routing │<br>        └─────┬─────┘      └─────┬─────┘      └─────┬─────┘<br>              │                  │                  │<br>              └──────────────────┼──────────────────┘<br>                                 ▼<br>                         ┌───────────────┐<br>                         │ API / Backend │<br>                         └───────┬───────┘<br>                                 │<br>                         ┌───────▼───────┐<br>                         │ DB / Services │<br>                         └───────────────┘</pre><p>Every boundary introduces a different class of failure.</p><p>Therefore, <strong>one type of test cannot protect the entire system.</strong></p><h3>1. The Testing Pyramid Is Not Enough</h3><p>Most developers learn this:</p><pre>             /\<br>            /  \<br>           / E2E\<br>          /------\<br>         /Integr. \<br>        /----------\<br>       /    Unit    \<br>      /--------------\</pre><p>The idea is simple:</p><ul><li>Many unit tests</li><li>Fewer integration tests</li><li>Even fewer E2E tests</li></ul><p>But in enterprise applications, I prefer thinking about <strong>risk and boundaries</strong>, rather than blindly following the pyramid.</p><p>A more practical model is:</p><pre>                 ┌──────────────────┐<br>                 │ Production / RUM │<br>                 └────────┬─────────┘<br>                          │<br>                 ┌────────▼─────────┐<br>                 │ Critical E2E     │<br>                 │ User Journeys    │<br>                 └────────┬─────────┘<br>                          │<br>              ┌───────────▼───────────┐<br>              │ Integration / Feature │<br>              │ Behaviour             │<br>              └───────────┬───────────┘<br>                          │<br>          ┌───────────────▼───────────────┐<br>          │ Unit / Component / Pure Logic │<br>          └───────────────────────────────┘</pre><p>The question shouldn’t be:</p><blockquote><em>“How many tests do we have?”</em></blockquote><p>It should be:</p><blockquote><strong><em>“What failures can escape our test suite?”</em></strong></blockquote><h3>2. The Enterprise Testing Strategy</h3><p>For a large React/Next.js application, I typically think about testing across these layers:</p><pre>┌───────────────────────────────────────────────┐<br>│                E2E TESTING                    │<br>│                                               │<br>│ Login → Search → Checkout → Payment           │<br>└───────────────────────┬───────────────────────┘<br>                        │<br>┌───────────────────────▼───────────────────────┐<br>│            INTEGRATION TESTING                │<br>│                                               │<br>│ Component + Redux + API + Router              │<br>└───────────────────────┬───────────────────────┘<br>                        │<br>┌───────────────────────▼───────────────────────┐<br>│           COMPONENT TESTING                   │<br>│                                               │<br>│ User interaction + UI behaviour               │<br>└───────────────────────┬───────────────────────┘<br>                        │<br>┌───────────────────────▼───────────────────────┐<br>│              UNIT TESTING                     │<br>│                                               │<br>│ Functions + reducers + selectors + utilities  │<br>└───────────────────────┬───────────────────────┘<br>                        │<br>┌───────────────────────▼───────────────────────┐<br>│              STATIC CHECKS                    │<br>│                                               │<br>│ TypeScript + ESLint + formatting              │<br>└───────────────────────────────────────────────┘</pre><p>Each layer has a different responsibility.</p><h3>3. Layer 1 — Static Validation</h3><p>Testing actually starts before runtime.</p><p>Typical enterprise pipelines include:</p><pre>Developer Commit<br>      │<br>      ▼<br>TypeScript<br>      │<br>      ▼<br>ESLint<br>      │<br>      ▼<br>Formatting<br>      │<br>      ▼<br>Build<br>      │<br>      ▼<br>Unit Tests<br>      │<br>      ▼<br>Integration Tests<br>      │<br>      ▼<br>E2E</pre><h3>TypeScript</h3><p>TypeScript catches entire categories of problems before the application runs.</p><p>For example:</p><pre>type User = {<br>  id: string;<br>  name: string;<br>};<br><br>function getUserName(user: User) {<br>  return user.name;<br>}</pre><p>Passing:</p><pre>getUserName({<br>  id: 123<br>});</pre><p>should fail during development/build rather than waiting for a test.</p><h3>Senior-level principle</h3><blockquote><strong><em>Don’t use runtime tests to catch problems the compiler can catch more cheaply.</em></strong></blockquote><h3>4. Layer 2 — Unit Testing</h3><p>Unit tests are ideal for deterministic logic.</p><p>Examples:</p><ul><li>utility functions</li><li>reducers</li><li>selectors</li><li>data transformations</li><li>validation</li><li>formatting</li><li>calculations</li><li>business rules</li></ul><p>For example:</p><pre>export function calculateDiscount(<br>  price: number,<br>  percentage: number<br>) {<br>  return price - price * (percentage / 100);<br>}</pre><p>Test:</p><pre>describe(&quot;calculateDiscount&quot;, () =&gt; {<br>  it(&quot;calculates discount correctly&quot;, () =&gt; {<br>    expect(calculateDiscount(1000, 10)).toBe(900);<br>  });<br>});</pre><p>These tests should be:</p><ul><li>fast</li><li>deterministic</li><li>isolated</li><li>easy to debug</li></ul><h3>5. What Should NOT Become a Unit Test?</h3><p>This is one of the lessons that becomes more important with experience.</p><p>Consider:</p><pre>&lt;Button<br>  className=&quot;primary-button&quot;<br>  data-testid=&quot;submit-button&quot;<br>&gt;<br>  Submit<br>&lt;/Button&gt;</pre><p>Testing:</p><pre>expect(button).toHaveClass(&quot;primary-button&quot;);</pre><p>might give you high coverage.</p><p>But what business behaviour are you protecting?</p><p>A better test might be:</p><pre>User clicks Submit<br>       ↓<br>Form validation runs<br>       ↓<br>API request triggered<br>       ↓<br>Loading state displayed<br>       ↓<br>Success response<br>       ↓<br>Success message displayed</pre><p>That’s closer to the behaviour users actually care about.</p><h3>6. Component Testing</h3><p>Component tests should validate <strong>user-visible behaviour</strong>.</p><p>Example:</p><pre>function LoginForm() {<br>  // ...<br>}</pre><p>Instead of testing internal implementation:</p><pre>expect(component.state.email).toBe(...)</pre><p>test the behaviour:</p><pre>Enter email<br>     ↓<br>Enter password<br>     ↓<br>Click Login<br>     ↓<br>API request<br>     ↓<br>Dashboard displayed</pre><p>This makes tests less coupled to implementation.</p><h3>7. Testing Library Mindset</h3><p>A useful principle is:</p><blockquote><strong><em>Test the application the way the user uses it.</em></strong></blockquote><p>Prefer:</p><pre>screen.getByRole(&quot;button&quot;, {<br>  name: /login/i<br>});</pre><p>over:</p><pre>container.querySelector(&quot;.login-button&quot;);</pre><p>Why?</p><p>Because CSS classes are implementation details.</p><p>The accessible role and user-facing name are part of the actual interface.</p><h3>8. Integration Testing</h3><p>This is where enterprise testing becomes much more interesting.</p><p>A real feature might involve:</p><pre>               Login Page<br>                   │<br>                   ▼<br>              React Form<br>                   │<br>                   ▼<br>                Redux<br>                   │<br>                   ▼<br>             API Layer<br>                   │<br>                   ▼<br>              Auth API<br>                   │<br>                   ▼<br>               Response<br>                   │<br>                   ▼<br>              Redux State<br>                   │<br>                   ▼<br>             Route Change<br>                   │<br>                   ▼<br>              Dashboard</pre><p>Testing every piece independently won’t necessarily prove that the entire flow works.</p><p>Integration testing verifies the <strong>contracts between those pieces</strong>.</p><h3>9. Mocking APIs Correctly</h3><p>One of the biggest mistakes I’ve seen is mocking too much.</p><p>Imagine:</p><pre>Component<br>   ↓<br>Hook<br>   ↓<br>Service<br>   ↓<br>API</pre><p>If every layer is mocked:</p><pre>Component → Mock Hook → Mock Service → Mock API</pre><p>your test can become meaningless.</p><p>You are essentially testing mocks.</p><p>A better approach is often:</p><pre>Component<br>   ↓<br>Hook<br>   ↓<br>Service<br>   ↓<br>Mock HTTP Server</pre><p>The application still executes most of its real logic.</p><p>Only the external dependency is controlled.</p><p>Tools such as <strong>MSW (Mock Service Worker)</strong> are useful for this style of testing.</p><h3>10. Redux Testing</h3><p>For Redux-based applications, I avoid testing implementation details unnecessarily.</p><p>Instead of testing:</p><pre>Did dispatch() happen exactly once?</pre><p>test:</p><pre>User action<br>    ↓<br>State changes<br>    ↓<br>UI changes</pre><p>Example:</p><pre>User clicks &quot;Add to Cart&quot;<br>          ↓<br>Redux action<br>          ↓<br>Reducer<br>          ↓<br>Cart state updated<br>          ↓<br>Cart count becomes 3</pre><p>That is a much stronger test.</p><h3>What should be unit tested?</h3><p>Good candidates:</p><ul><li>reducers</li><li>selectors</li><li>pure transformations</li><li>complex business logic</li></ul><h3>What should be integration tested?</h3><ul><li>component + store</li><li>async actions</li><li>state + UI</li><li>feature workflows</li></ul><h3>11. E2E Testing</h3><p>E2E tests should represent <strong>critical business journeys</strong>.</p><p>For example, an e-commerce application:</p><pre>              ┌────────────┐<br>              │   Login    │<br>              └─────┬──────┘<br>                    ↓<br>              ┌────────────┐<br>              │   Search   │<br>              └─────┬──────┘<br>                    ↓<br>              ┌────────────┐<br>              │ Product    │<br>              └─────┬──────┘<br>                    ↓<br>              ┌────────────┐<br>              │ Add Cart   │<br>              └─────┬──────┘<br>                    ↓<br>              ┌────────────┐<br>              │ Checkout   │<br>              └─────┬──────┘<br>                    ↓<br>              ┌────────────┐<br>              │  Payment   │<br>              └─────┬──────┘<br>                    ↓<br>              ┌────────────┐<br>              │ Confirmation│<br>              └────────────┘</pre><p>You don’t need thousands of E2E tests.</p><p>You need the <strong>right journeys</strong>.</p><h3>12. Playwright for Enterprise E2E</h3><p>For modern applications, Playwright is particularly useful for:</p><ul><li>Chromium</li><li>Firefox</li><li>WebKit</li><li>parallel execution</li><li>tracing</li><li>screenshots</li><li>videos</li><li>network interception</li><li>multiple contexts</li><li>authentication state</li></ul><p>Example:</p><pre>test(&quot;user can complete checkout&quot;, async ({ page }) =&gt; {<br>  await page.goto(&quot;/products&quot;);<br><br>await page.getByRole(&quot;button&quot;, {<br>    name: &quot;Add to cart&quot;<br>  }).click();<br>  await page.getByRole(&quot;link&quot;, {<br>    name: &quot;Checkout&quot;<br>  }).click();<br>  await page.getByRole(&quot;button&quot;, {<br>    name: &quot;Place order&quot;<br>  }).click();<br>  await expect(<br>    page.getByText(&quot;Order confirmed&quot;)<br>  ).toBeVisible();<br>});</pre><p>Notice that the test describes <strong>business behaviour</strong>, not React implementation.</p><h3>13. The Flaky Test Problem</h3><p>This is one of the biggest challenges in enterprise testing.</p><p>You may see:</p><pre>CI Run #1 → PASS<br>CI Run #2 → FAIL<br>CI Run #3 → PASS<br>CI Run #4 → PASS<br>CI Run #5 → FAIL</pre><p>Developers start saying:</p><blockquote><em>“It’s just a flaky test.”</em></blockquote><p>That’s dangerous.</p><p>A flaky test is still a <strong>production engineering problem</strong> because eventually developers stop trusting the pipeline.</p><h3>14. Common Causes of Flaky Tests</h3><p>❌ Arbitrary waits</p><pre>await page.waitForTimeout(3000);</pre><p>This is usually a smell.</p><p>❌ Race conditions</p><pre>API request<br>   ↓<br>UI update<br>   ↓<br>Test runs assertion too early</pre><p>❌ Shared test state</p><pre>Test A modifies database<br>       ↓<br>Test B assumes clean state</pre><p>❌ Random test data</p><p>❌ Time-dependent behaviour</p><p>❌ External services</p><p>❌ Animations</p><p>❌ Incorrect selectors</p><p>❌ Parallel execution conflicts</p><h3>15. Better Synchronization</h3><p>Instead of:</p><pre>await page.waitForTimeout(2000);</pre><p>prefer waiting for a meaningful condition:</p><pre>await expect(<br>  page.getByRole(&quot;heading&quot;, {<br>    name: &quot;Dashboard&quot;<br>  })<br>).toBeVisible();</pre><p>The difference seems small.</p><p>At scale, it makes a huge difference.</p><h3>16. Test Data Strategy</h3><p>Enterprise testing becomes difficult when test data isn’t controlled.</p><p>A useful architecture is:</p><pre>                Test<br>                  │<br>                  ▼<br>           Test Data Factory<br>                  │<br>        ┌─────────┼─────────┐<br>        ▼         ▼         ▼<br>      User      Order     Product<br>        │         │         │<br>        └─────────┼─────────┘<br>                  ▼<br>             Application</pre><p>Instead of:</p><pre>const user = {<br>  name: &quot;John&quot;,<br>  email: &quot;john@test.com&quot;<br>};</pre><p>everywhere, create factories:</p><pre>const user = createUser({<br>  role: &quot;admin&quot;<br>});</pre><p>This keeps tests maintainable.</p><h3>17. Authentication in E2E Tests</h3><p>Logging in through the UI before every test is expensive.</p><p>Instead:</p><pre>Authentication Setup<br>        │<br>        ▼<br>Create authenticated state<br>        │<br>        ▼<br>Save storage state<br>        │<br>        ▼<br>Reuse in tests</pre><p>Playwright supports reusable authentication state.</p><p>This can dramatically reduce test execution time.</p><h3>18. Visual Regression Testing</h3><p>Functional tests can tell you:</p><blockquote><em>“The button exists.”</em></blockquote><p>They may not tell you:</p><blockquote><em>“The entire layout moved 40px after the CSS change.”</em></blockquote><p>Visual regression testing can help detect:</p><ul><li>layout changes</li><li>broken responsive design</li><li>typography changes</li><li>spacing regressions</li><li>unexpected component changes</li></ul><p>A typical workflow:</p><pre>Code Change<br>     ↓<br>Build<br>     ↓<br>Render Page<br>     ↓<br>Screenshot<br>     ↓<br>Compare Baseline<br>     ↓<br>Difference?<br>   /     \<br> YES      NO<br>  ↓        ↓<br>Review    Pass</pre><p>But visual testing also requires discipline.</p><p>Not every pixel difference is a bug.</p><h3>19. Accessibility Testing</h3><p>Accessibility should not be treated as a final QA phase.</p><p>It belongs inside the development lifecycle.</p><p>Test:</p><ul><li>keyboard navigation</li><li>focus management</li><li>labels</li><li>ARIA semantics</li><li>contrast</li><li>screen-reader behaviour</li><li>dialogs</li><li>forms</li><li>error messages</li></ul><p>For example:</p><pre>Keyboard<br>   ↓<br>Tab<br>   ↓<br>Focus<br>   ↓<br>Button<br>   ↓<br>Enter<br>   ↓<br>Action</pre><p>If a critical workflow cannot be completed using a keyboard, that’s a functional problem — not merely an accessibility enhancement.</p><h3>20. Contract Testing</h3><p>Enterprise frontends often depend on multiple backend teams.</p><p>Consider:</p><pre>Frontend Team<br>      │<br>      ▼<br>   API Gateway<br>      │<br> ┌────┼────┐<br> ▼    ▼    ▼<br>API A API B API C</pre><p>The backend changes:</p><pre>{<br>  &quot;userName&quot;: &quot;Hareesh&quot;<br>}</pre><p>while frontend expects:</p><pre>{<br>  &quot;name&quot;: &quot;Hareesh&quot;<br>}</pre><p>Everything compiles.</p><p>Unit tests may pass.</p><p>Production breaks.</p><p>This is where <strong>API contract testing</strong> becomes valuable.</p><h3>21. Testing Next.js Applications</h3><p>Modern Next.js applications introduce additional testing considerations:</p><pre>Next.js Application<br>       │<br> ┌─────┼───────────┐<br> ▼     ▼           ▼<br>SSR   Server      Client<br>      Components  Components</pre><p>You need to consider:</p><ul><li>Server Components</li><li>Client Components</li><li>routing</li><li>loading states</li><li>error states</li><li>server-side data fetching</li><li>hydration</li><li>middleware</li><li>authentication</li><li>caching</li><li>API routes</li></ul><p>A component that works correctly in a pure client-side environment isn’t automatically validated for its actual server/client boundary.</p><h3>22. Testing Error States</h3><p>One of the most commonly missed areas:</p><pre>Happy Path<br>──────────────<br>API → 200 → UI</pre><p>But production looks more like:</p><pre>              API<br>               │<br>      ┌────────┼────────┐<br>      ▼        ▼        ▼<br>     200      401      500<br>      │        │        │<br>      ▼        ▼        ▼<br>    Success   Login    Retry/Error</pre><p>You should explicitly test:</p><ul><li>loading</li><li>success</li><li>empty</li><li>unauthorized</li><li>forbidden</li><li>validation errors</li><li>server errors</li><li>timeout</li><li>network failure</li><li>partial failure</li></ul><h3>23. The State Matrix</h3><p>For complex applications, I like thinking in terms of a <strong>state matrix</strong>.</p><p>For a data table:</p><h3>UI State → Expected UI</h3><p><strong>Loading</strong> → Skeleton<br><strong>Success</strong> → Data<br><strong>Empty</strong> → Empty state<br><strong>401</strong> → Login<br><strong>403</strong> → Permission message<br><strong>404</strong> → Not found<br><strong>500</strong> → Error state<br><strong>Network failure</strong> → Retry<br><strong>Slow API</strong> → Loading indicator</p><p>Instead of writing one test for:</p><blockquote><em>“Table renders.”</em></blockquote><p>write tests around these meaningful states.</p><h3>24. Test Coverage — Don’t Worship the Number</h3><p>Suppose your project has:</p><pre>95% coverage</pre><p>Sounds excellent.</p><p>But what if:</p><pre>Checkout workflow → 0 E2E tests<br>Authentication → 0 integration tests<br>Payment → 0 failure tests</pre><p>Then the 95% number is misleading.</p><p>Coverage should be a <strong>signal</strong>, not the definition of quality.</p><p>I would rather have:</p><pre>80% meaningful coverage</pre><p>than:</p><pre>98% meaningless coverage</pre><h3>25. What Should We Measure?</h3><p>A mature testing strategy measures more than coverage.</p><h3>Useful metrics</h3><pre>Test Pass Rate<br>Flaky Test Rate<br>Test Execution Time<br>Critical Journey Coverage<br>Defect Escape Rate<br>Mean Time to Fix<br>Production Regression Rate</pre><p>One particularly useful metric:</p><h3>Defect Escape Rate</h3><pre>Bugs found before production<br>          vs<br>Bugs found after production</pre><p>If coverage increases but production defects don’t decrease, your testing strategy may be targeting the wrong things.</p><h3>26. CI/CD Testing Architecture</h3><p>A scalable pipeline might look like:</p><pre>                    Pull Request<br>                         │<br>                         ▼<br>                 ┌──────────────┐<br>                 │ TypeScript   │<br>                 └──────┬───────┘<br>                        ▼<br>                 ┌──────────────┐<br>                 │ ESLint       │<br>                 └──────┬───────┘<br>                        ▼<br>                 ┌──────────────┐<br>                 │ Unit Tests   │<br>                 └──────┬───────┘<br>                        ▼<br>                 ┌──────────────┐<br>                 │ Integration  │<br>                 └──────┬───────┘<br>                        ▼<br>                 ┌──────────────┐<br>                 │ Build        │<br>                 └──────┬───────┘<br>                        ▼<br>              ┌───────────────────┐<br>              │ Preview Environment│<br>              └─────────┬─────────┘<br>                        ▼<br>                 ┌──────────────┐<br>                 │ Playwright   │<br>                 │ E2E          │<br>                 └──────┬───────┘<br>                        ▼<br>                 ┌──────────────┐<br>                 │ Deploy       │<br>                 └──────────────┘</pre><h3>27. Parallelizing Tests</h3><p>Enterprise suites can become expensive.</p><p>Imagine:</p><pre>1,500 tests<br>×<br>5 seconds<br>=<br>7,500 seconds</pre><p>You cannot afford to run everything sequentially.</p><p>Instead:</p><pre>                Test Suite<br>                    │<br>        ┌───────────┼───────────┐<br>        ▼           ▼           ▼<br>     Worker 1    Worker 2    Worker 3<br>        │           │           │<br>      Tests       Tests       Tests<br>        │           │           │<br>        └───────────┼───────────┘<br>                    ▼<br>                  Result</pre><p>Parallelization can significantly reduce CI duration — but only if tests are properly isolated.</p><h3>28. The Test Ownership Model</h3><p>One of the biggest architectural lessons I’ve learned:</p><blockquote><strong><em>Testing cannot be owned entirely by QA.</em></strong></blockquote><p>A healthy enterprise model is:</p><pre>Developer<br>   │<br>   ├── Unit Tests<br>   ├── Component Tests<br>   └── Integration Tests<br><br>QA / SDET<br>   │<br>   ├── E2E Strategy<br>   ├── Regression<br>   └── Quality Automation<br>Platform / DevOps<br>   │<br>   ├── CI/CD<br>   ├── Test Infrastructure<br>   └── Reporting<br>Product<br>   │<br>   └── Critical User Journeys</pre><p>Quality is a <strong>shared responsibility</strong>.</p><h3>29. What I’ve Learned After 10+ Years</h3><p>If I had to summarize the most important lessons:</p><h3>1. Don’t maximize test count.</h3><p>Maximize <strong>confidence</strong>.</p><h3>2. Don’t test implementation details.</h3><p>Test <strong>behaviour</strong>.</p><h3>3. Don’t mock everything.</h3><p>Mock <strong>external boundaries</strong>.</p><h3>4. Don’t make every test E2E.</h3><p>Keep most tests closer to the code.</p><h3>5. Don’t ignore flaky tests.</h3><p>They destroy trust in the pipeline.</p><h3>6. Don’t rely solely on coverage.</h3><p>Measure <strong>escaped defects and critical workflows</strong>.</p><h3>7. Don’t test only happy paths.</h3><p>Production failures usually happen elsewhere.</p><h3>8. Don’t make QA the only owner of quality.</h3><p>Developers own the quality of the code they write.</p><h3>30. My Enterprise Testing Stack</h3><p>A modern React/Next.js enterprise project could look something like:</p><pre>┌─────────────────────────────────────────────┐<br>│               Quality Layer                 │<br>├─────────────────────────────────────────────┤<br>│                                             │<br>│ TypeScript          → Static Safety         │<br>│ ESLint              → Code Quality          │<br>│                                             │<br>│ Jest / Vitest       → Unit Tests            │<br>│ Testing Library     → Component Tests       │<br>│ MSW                 → API Mocking            │<br>│                                             │<br>│ Playwright          → E2E Tests             │<br>│ Accessibility       → A11y Validation       │<br>│ Visual Testing      → UI Regression         │<br>│                                             │<br>│ CI/CD               → Automated Validation  │<br>│ Monitoring / RUM    → Production Feedback   │<br>│                                             │<br>└─────────────────────────────────────────────┘</pre><p>The exact tools can change.</p><p>The <strong>principles don’t</strong>.</p><h3>31. The Testing Strategy I Would Use Today</h3><p>For a large React/Next.js application, my starting point would be:</p><pre>                  ┌─────────────────┐<br>                  │ Critical E2E    │<br>                  │     10–15%      │<br>                  └────────┬────────┘<br>                           │<br>                  ┌────────▼────────┐<br>                  │ Integration     │<br>                  │     20–30%      │<br>                  └────────┬────────┘<br>                           │<br>                  ┌────────▼────────┐<br>                  │ Component       │<br>                  │     25–35%      │<br>                  └────────┬────────┘<br>                           │<br>                  ┌────────▼────────┐<br>                  │ Unit            │<br>                  │     30–40%      │<br>                  └─────────────────┘</pre><p>These percentages aren’t rigid rules.</p><p>The distribution should depend on:</p><ul><li>business risk</li><li>application complexity</li><li>team maturity</li><li>release frequency</li><li>regulatory requirements</li><li>number of integrations</li><li>cost of failure</li></ul><h3>32. The Real Goal</h3><p>The ultimate testing architecture looks like this:</p><pre>                Developer<br>                      │<br>                      ▼<br>               ┌─────────────┐<br>               │ Code Change │<br>               └──────┬──────┘<br>                      │<br>                      ▼<br>              ┌───────────────┐<br>              │ Static Checks │<br>              └───────┬───────┘<br>                      │<br>                      ▼<br>              ┌───────────────┐<br>              │ Unit Tests    │<br>              └───────┬───────┘<br>                      │<br>                      ▼<br>              ┌───────────────┐<br>              │ Integration   │<br>              └───────┬───────┘<br>                      │<br>                      ▼<br>              ┌───────────────┐<br>              │ E2E           │<br>              └───────┬───────┘<br>                      │<br>                      ▼<br>                 Deployment<br>                      │<br>                      ▼<br>             ┌────────────────┐<br>             │ Real Users     │<br>             └───────┬────────┘<br>                     │<br>                     ▼<br>             ┌────────────────┐<br>             │ Observability  │<br>             └───────┬────────┘<br>                     │<br>                     ▼<br>               Feedback Loop<br>                     │<br>                     └──────────► Engineering</pre><p><strong>That’s the real definition of frontend quality.</strong></p><p>Not:</p><blockquote><em>“We have 90% test coverage.”</em></blockquote><p>But:</p><blockquote><strong><em>“We can make changes quickly, detect regressions early, deploy confidently, and know when production behaves differently from what we expected.”</em></strong></blockquote><h3>🎯 Interview Questions From This Topic</h3><p>If you’re interviewing for a <strong>Senior Frontend / Lead / Staff Engineer</strong> position, expect questions like:</p><h3>Architecture</h3><ol><li>How would you design a testing strategy for a large React application?</li><li>How do you decide between unit, integration and E2E tests?</li><li>What should never be tested using E2E?</li><li>How would you test a Redux-heavy application?</li><li>How would you test a Next.js application with SSR and client components?</li></ol><h3>Practical</h3><ol><li>How do you debug flaky Playwright tests?</li><li>How do you reduce E2E execution time?</li><li>How do you handle authentication in E2E tests?</li><li>How do you mock APIs?</li><li>When would you use MSW?</li><li>How do you test error states?</li><li>How do you test WebSockets?</li><li>How do you test file uploads?</li><li>How do you test accessibility?</li></ol><h3>Leadership</h3><ol><li>Who owns frontend quality?</li><li>What test coverage percentage do you target?</li><li>How do you convince a team to invest in testing?</li><li>How do you handle a legacy application with no tests?</li><li>How do you decide which tests to remove?</li><li>How do you measure whether your testing strategy is actually working?</li></ol><h3>Final Thought</h3><p>After 10+ years, I don’t see testing as a separate phase after development.</p><p>I see it as part of <strong>frontend architecture</strong>.</p><p>A well-designed frontend makes itself easier to test.</p><p>A poorly designed frontend often requires enormous amounts of mocking, brittle selectors, complicated setup, and slow E2E suites.</p><p>And that’s one of the strongest lessons I’ve learned:</p><blockquote><strong><em>Testability is an architectural property — not just a testing activity.</em></strong></blockquote><p>If you’re designing a React application today, don’t ask:</p><p><strong>“How will we test this?”</strong></p><p>Ask the architectural question first:</p><p><strong>“Have we designed this in a way that can be tested reliably?”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10402d870e5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Components Are Getting Too Big: How to Refactor Without Breaking Production]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/react-components-are-getting-too-big-how-to-refactor-without-breaking-production-3c29cac98d03?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c29cac98d03</guid>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 12:03:09 GMT</pubDate>
            <atom:updated>2026-08-30T12:03:09.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuqAFqSrLmyCJnEDjJrRGA.png" /></figure><h3>A production-focused guide to decomposing large React components safely — without introducing regressions, unnecessary abstractions, or architectural chaos.</h3><p>After 10+ years of frontend development, I’ve found that one of the most dangerous things in a mature React application isn’t necessarily bad code.</p><p>It’s <strong>code that works, but nobody is comfortable changing</strong>.</p><p>You know the component.</p><p>It started at 150 lines.</p><p>Then came filtering.</p><p>Then pagination.</p><p>Then API integration.</p><p>Then permissions.</p><p>Then validation.</p><p>Then modals.</p><p>Then exports.</p><p>Then analytics.</p><p>Then a few more useEffect’s.</p><p>Eventually, you end up with something like:</p><pre>function ProductManagement() {<br>  // API calls<br><br>  // Redux selectors<br>  // Local state<br>  // Filters<br>  // Pagination<br>  // Sorting<br>  // Selection<br>  // Permissions<br>  // Validation<br>  // Business rules<br>  // Export<br>  // Modal handling<br>  // Analytics<br>  // Hundreds of lines of JSX<br>}</pre><p>The file might now be 1,000+ lines.</p><p>But here’s the important distinction:</p><blockquote><strong><em>A large component is not necessarily a problem. A component with too many reasons to change is.</em></strong></blockquote><p>That’s what this article is about.</p><p>Not how to split a 1,000-line file into ten files.</p><p>But how to <strong>reduce complexity without changing production behavior</strong>.</p><h3>1. The First Mistake: Measuring Components by Line Count</h3><p>A common rule is:</p><blockquote><em>“Anything above 300 lines should be refactored.”</em></blockquote><p>I don’t agree with that.</p><p>Consider a component that contains 500 lines of declarative UI with very little logic.</p><p>Now consider another component with 200 lines containing:</p><ul><li>API calls</li><li>state transitions</li><li>permissions</li><li>validation</li><li>effects</li><li>business rules</li><li>conditional rendering</li></ul><p>The second component may be much harder to maintain.</p><p>The better metric is <strong>cognitive complexity</strong>.</p><p>Ask yourself:</p><blockquote><em>“How much context does another developer need to understand this component before making a safe change?”</em></blockquote><p>That’s a much more useful question.</p><h3>Signs that complexity is becoming a problem</h3><p>Look for:</p><ul><li>Multiple unrelated useEffect&#39;s</li><li>Too many independent state variables</li><li>API calls inside UI components</li><li>Business rules inside click handlers</li><li>Deep conditional rendering</li><li>Permission logic mixed with presentation</li><li>Repeated data transformations</li><li>Multiple responsibilities sharing the same state</li><li>Large prop chains</li><li>Duplicate API requests</li><li>Tests that require rendering an entire page for a small business rule</li><li>Frequent merge conflicts</li></ul><p>And one particularly important signal:</p><blockquote><strong><em>Developers are afraid to modify the component.</em></strong></blockquote><p>When the team starts saying:</p><blockquote><em>“Don’t touch that component; something always breaks.”</em></blockquote><p>the problem has moved beyond code style.</p><p>It has become an engineering-risk problem.</p><h3>2. Before Refactoring: Understand What the Component Actually Does</h3><p>The first thing I do isn’t opening the editor and extracting JSX.</p><p>I map the responsibilities.</p><p>Suppose we have:</p><pre>ProductManagement<br>│<br>├── Fetch products<br>├── Transform API response<br>├── Filter products<br>├── Sort products<br>├── Manage selection<br>├── Validate permissions<br>├── Export data<br>├── Open/close dialogs<br>├── Handle errors<br>└── Render UI</pre><p>That’s already telling us something.</p><p>The component isn’t really one responsibility.</p><p>It’s acting as:</p><pre>              ProductManagement<br>                     │<br>       ┌─────────────┼─────────────┐<br>       │             │             │<br>       ▼             ▼             ▼<br>     Data         Behavior      Presentation<br>       │             │             │<br>       ▼             ▼             ▼<br>     API       Filters/Rules      Table<br>     State     Selection          Dialog<br>               Validation         Actions</pre><p>And this is where a good refactoring starts.</p><p>Not with files.</p><p>With <strong>boundaries</strong>.</p><h3>3. The Architecture We Actually Want</h3><p>The goal isn’t:</p><pre>BigComponent.tsx<br>      ↓<br>5 smaller .tsx files</pre><p>That’s only file splitting.</p><p>What we want is:</p><pre>ProductPage<br>     │<br>     ├─────────────── UI<br>     │<br>     ├─────────────── Hooks / Behavior<br>     │<br>     ├─────────────── Domain Logic<br>     │<br>     └─────────────── Data Access</pre><p>A practical feature-oriented structure could look like:</p><pre>features/products/<br>│<br>├── components/<br>│   ├── ProductFilters.tsx<br>│   ├── ProductTable.tsx<br>│   ├── ProductActions.tsx<br>│   └── ProductDialog.tsx<br>│<br>├── hooks/<br>│   ├── useProducts.ts<br>│   ├── useProductFilters.ts<br>│   └── useProductSelection.ts<br>│<br>├── services/<br>│   └── productService.ts<br>│<br>├── utils/<br>│   ├── productMapper.ts<br>│   └── productValidator.ts<br>│<br>└── types.ts</pre><p>Notice that this is not simply a folder convention.</p><p>Each part has an <strong>ownership boundary</strong>.</p><ul><li>ProductTable owns table presentation.</li><li>useProductFilters owns filter behavior.</li><li>useProducts owns the React-facing data behavior.</li><li>productService owns communication with the backend.</li><li>productValidator owns pure validation rules.</li></ul><p>This separation makes the system easier to reason about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*if1ccsDiu-IaiXty" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*wr8rSGrEOpEifOZ7" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aD6PVpBEUfd5XdAm" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*qn2mik-Vvhg4nFW1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q3wMFpp6yF4g3EhL" /></figure><p>The important architectural idea is:</p><pre>UI<br> ↓<br>Behavior<br> ↓<br>Data Access<br> ↓<br>Backend</pre><p>rather than:</p><pre>UI<br> ↕<br>State<br> ↕<br>API<br> ↕<br>Business Logic<br> ↕<br>UI</pre><p>where everything knows about everything else.</p><h3>4. Extract Pure Logic Before React Logic</h3><p>This is one of the safest places to begin.</p><p>Suppose the component contains:</p><pre>const getProductStatus = (product: Product) =&gt; {<br>  if (!product.active) {<br>    return &quot;Inactive&quot;;<br>  }<br><br>  if (product.stock &lt;= 0) {<br>    return &quot;Out of Stock&quot;;<br>  }<br>  return &quot;Available&quot;;<br>};</pre><p>This function doesn’t need:</p><ul><li>Reac</li><li>useState</li><li>useEffect</li><li>Redux</li><li>Context</li></ul><p>So why should it live inside a component?</p><p>Move it into:</p><pre>utils/productStatus.ts</pre><p>Now it can be tested independently:</p><pre>describe(&quot;getProductStatus&quot;, () =&gt; {<br>  it(&quot;returns inactive for disabled products&quot;, () =&gt; {<br>    expect(<br>      getProductStatus({<br>        active: false,<br>        stock: 10<br>      })<br>    ).toBe(&quot;Inactive&quot;);<br>  });<br>});</pre><p>This is a very powerful refactoring step.</p><p>The business rule is now independent of React rendering.</p><h3>A good rule</h3><blockquote><strong><em>If a piece of logic doesn’t need React, don’t make React responsible for it.</em></strong></blockquote><h3>5. Then Extract React-Specific Behavior</h3><p>Now consider this:</p><pre>const [products, setProducts] = useState([]);<br>const [loading, setLoading] = useState(false);<br>const [error, setError] = useState(null);<br><br>useEffect(() =&gt; {<br>  setLoading(true);<br>  fetchProducts()<br>    .then(setProducts)<br>    .catch(setError)<br>    .finally(() =&gt; setLoading(false));<br>}, []);</pre><p>This is behavior.</p><p>It can become:</p><pre>function useProducts() {<br>  const [products, setProducts] = useState([]);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    setLoading(true);<br>    fetchProducts()<br>      .then(setProducts)<br>      .catch(setError)<br>      .finally(() =&gt; setLoading(false));<br>  }, []);<br>  return {<br>    products,<br>    loading,<br>    error<br>  };<br>}</pre><p>The page becomes:</p><pre>function ProductManagement() {<br>  const {<br>    products,<br>    loading,<br>    error<br>  } = useProducts();<br><br>// composition<br>}</pre><p>Now the component has less implementation detail.</p><p>It primarily describes <strong>what the screen is made of</strong>.</p><h3>6. But Don’t Turn Everything Into a Custom Hook</h3><p>This is where over-engineering starts.</p><p>I’ve seen codebases where every function becomes:</p><pre>useProductName()<br>useProductStatus()<br>useProductLabel()<br>useProductColor()<br>useProductFormatter()</pre><p>That’s not better architecture.</p><p>A custom hook is appropriate when you are encapsulating React behavior such as:</p><ul><li>State</li><li>Effects</li><li>Context</li><li>Other hooks</li><li>Subscriptions</li><li>React-specific lifecycle behavior</li></ul><p>If you simply need:</p><pre>formatProductName(product)</pre><p>then write:</p><pre>formatProductName(product)</pre><p>Don’t turn it into:</p><pre>useProductName(product)</pre><p>just because the project uses hooks heavily.</p><blockquote><strong><em>Abstraction should reduce mental load, not increase it.</em></strong></blockquote><h3>7. State Ownership Is More Important Than Component Size</h3><p>One of the biggest architectural decisions during refactoring is deciding where state belongs.</p><p>Consider:</p><pre>Application State<br>│<br>├── Server State<br>│   ├── Products<br>│   ├── Orders<br>│   └── Customers<br>│<br>├── Global UI State<br>│   ├── Authentication<br>│   ├── Theme<br>│   └── Application Preferences<br>│<br>└── Local UI State<br>    ├── Modal<br>    ├── Selected Tab<br>    └── Temporary Form State</pre><p>Don’t automatically put everything into Redux.</p><p>Don’t automatically keep everything local either.</p><p>Ask:</p><ol><li>Who consumes the state?</li><li>How long does it need to live?</li><li>Is it server-owned or client-owned?</li><li>Does it need to survive navigation?</li><li>Is there already a source of truth?</li></ol><p>A simple rule that works well:</p><blockquote><strong><em>Keep state as close as possible to where it is consumed, but no closer.</em></strong></blockquote><h3>8. The “God Parent” Problem</h3><p>Refactoring can create another problem.</p><p>The original component gets split, but now the parent contains:</p><pre>&lt;ProductPage<br>  products={products}<br>  filters={filters}<br>  setFilters={setFilters}<br>  selected={selected}<br>  setSelected={setSelected}<br>  permissions={permissions}<br>  loading={loading}<br>  error={error}<br>  onExport={handleExport}<br>  onDelete={handleDelete}<br>  onEdit={handleEdit}<br>/&gt;</pre><p>The component is smaller.</p><p>But the coupling is still there.</p><p>You’ve simply moved the complexity upward.</p><p>Before reaching for Context or Redux, ask:</p><blockquote><strong><em>Is this actually shared state, or is the component boundary wrong?</em></strong></blockquote><p>Context is useful when multiple descendants genuinely need the same value.</p><p>Redux or another global state solution is useful when state truly has application-wide ownership.</p><p>Neither should be used as a band-aid for poor component boundaries.</p><h3>9. The Strangler Pattern Works Extremely Well for Production React</h3><p>This is one of my favorite approaches for large production applications.</p><p>Don’t rewrite the entire component.</p><p>Replace it gradually.</p><h3>Stage 1</h3><pre>BigComponent<br>└── Everything</pre><h3>Stage 2</h3><pre>BigComponent<br>├── ProductFilters<br>└── Everything else</pre><h3>Stage 3</h3><pre>BigComponent<br>├── ProductFilters<br>├── ProductTable<br>└── Everything else</pre><h3>Stage 4</h3><pre>ProductPage<br>├── ProductFilters<br>├── ProductTable<br>├── ProductActions<br>└── ProductDialog</pre><p>Eventually the old implementation disappears.</p><p>This is essentially the <strong>Strangler Fig pattern applied to frontend refactoring</strong>: replace one capability at a time while the rest of the application continues to work. (<a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/strangler-fig.html?utm_source=chatgpt.com">AWS Documentation</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aS_F7voxfuPoUOza" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RCA0Jgsql-QmMmeC" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pyeyQ0GsD7v26qwa" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Miol7Au57UBs0kru" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bo-bzkg-WDk_3TAP" /></figure><p>The key advantage is that production never has to jump from:</p><pre>100% Legacy</pre><p>to:</p><pre>100% New</pre><p>in a single release.</p><h3>10. Keep the Public Contract Stable</h3><p>This is particularly important in enterprise applications.</p><p>Imagine multiple screens already consume:</p><pre>&lt;ProductManagement<br>  clientId={clientId}<br>  onSelect={handleSelect}<br>/&gt;</pre><p>During the refactor, try to keep that contract unchanged.</p><p>Internally you can completely reorganize the implementation:</p><pre>Existing Public API<br>        │<br>        ▼<br> ProductManagement<br>        │<br>   ┌────┼────┐<br>   ▼    ▼    ▼<br> Hooks  UI  Services</pre><p>The consumer doesn’t need to know that you’ve changed the internal architecture.</p><p>This dramatically reduces the blast radius.</p><p>It is particularly important for:</p><ul><li>Shared component libraries</li><li>Design systems</li><li>Micro-frontends</li><li>Enterprise applications</li><li>Components consumed by multiple teams</li></ul><h3>11. useEffect Is Often Where the Complexity Hides</h3><p>Large components often contain effects like:</p><pre>useEffect(() =&gt; {<br>  fetchData();<br><br>  updateAnalytics();<br>  validatePermissions();<br>  calculateSomething();<br>}, [dependency]);</pre><p>This is a smell.</p><p>Not necessarily because there are multiple statements, but because they may represent <strong>four different responsibilities</strong>.</p><p>Separate them where appropriate:</p><pre>useEffect(() =&gt; {<br>  fetchData();<br>}, [dependency]);<br><br>useEffect(() =&gt; {<br>  updateAnalytics();<br>}, [analyticsDependency]);</pre><p>And be careful not to use effects for values that can simply be derived.</p><p>Instead of:</p><pre>const [filteredProducts, setFilteredProducts] = useState([]);<br><br>useEffect(() =&gt; {<br>  setFilteredProducts(<br>    products.filter(product =&gt; product.active)<br>  );<br>}, [products]);</pre><p>prefer:</p><pre>const filteredProducts = products.filter(<br>  product =&gt; product.active<br>);</pre><p>unless there is a genuine reason to cache or synchronize the result.</p><h3>12. Separate Server State From UI State</h3><p>This distinction becomes extremely valuable in larger applications.</p><p>For example:</p><pre>                     ProductPage<br>                        │<br>            ┌───────────┴───────────┐<br>            │                       │<br>       Server State             UI State<br>            │                       │<br>      ┌─────┴─────┐          ┌──────┴──────┐<br>      │           │          │             │<br>   products    loading     filter        modal<br>   error       status      selected      tab</pre><p>The product list is fundamentally different from whether a modal is open.</p><p>The backend owns the product data.</p><p>The browser owns whether the modal is open.</p><p>Treating those as the same category of state often makes components harder to reason about.</p><h3>13. The Refactoring Flow</h3><p>A production refactor should look more like this:</p><pre>Identify<br>   ↓<br>Understand<br>   ↓<br>Protect<br>   ↓<br>Extract<br>   ↓<br>Test<br>   ↓<br>Validate<br>   ↓<br>Deploy<br>   ↓<br>Measure<br>   ↓<br>Repeat</pre><p>Not:</p><pre>Delete component<br>      ↓<br>Rewrite everything<br>      ↓<br>Hope production works</pre><p>That difference is what separates a production refactor from a greenfield rewrite.</p><h3>14. How the Data Flow Should Look</h3><p>Once responsibilities are separated, the runtime flow becomes easier to reason about:</p><pre>User<br> │<br> ▼<br>ProductPage<br> │<br> ▼<br>useProductFilters<br> │<br> ▼<br>useProducts<br> │<br> ▼<br>ProductService<br> │<br> ▼<br>API<br> │<br> ▼<br>Backend<br> │<br> ▼<br>ProductService<br> │<br> ▼<br>useProducts<br> │<br> ▼<br>ProductTable<br> │<br> ▼<br>Updated UI</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*iP9KWmMtwuXDvns6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*3kE-2zKIzlHT4LH3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9J3lAMK5sj9a4S10" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*8vv24a-vEqdWWyog" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/0*_auOfr7VK5KkCIqZ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i7j7ss-FrmpY73yU" /></figure><p>The architectural principle is simple:</p><pre>Presentation<br>      ↓<br>Behavior<br>      ↓<br>Data Access<br>      ↓<br>Backend</pre><p>The table shouldn’t know how authentication works.</p><p>The API service shouldn’t know how the table is rendered.</p><p>The business rule shouldn’t know whether the UI uses a modal or a drawer.</p><p>That’s <strong>separation of concerns with a purpose</strong>.</p><h3>15. The Most Dangerous Regression: Duplicate API Calls</h3><p>This deserves its own section because I’ve seen it happen repeatedly during refactoring.</p><p>Before:</p><pre>ProductPage<br>     │<br>     └── fetchProducts()</pre><p>After:</p><pre>ProductPage<br>   │<br>   ├── useProducts()<br>   │<br>   └── ProductTable<br>          │<br>          └── useProducts()</pre><p>You have now potentially introduced two requests.</p><p>The code may look cleaner.</p><p>Production behavior is worse.</p><p>Whenever you extract data-fetching logic, ask:</p><blockquote><strong><em>Who owns this server state?</em></strong></blockquote><p>There should be one clear source of truth.</p><p>If multiple consumers need the same remote data, use an appropriate caching/shared-server-state strategy rather than independently fetching the same resource from multiple components.</p><h3>16. Testing Is Your Safety Net</h3><p>Before touching a critical component, identify its business-critical behavior.</p><p>For example:</p><pre>Product Management<br>│<br>├── Filter products<br>├── Select products<br>├── Edit product<br>├── Delete product<br>├── Export products<br>└── Permission handling</pre><p>Then protect those behaviors.</p><h3>Unit tests</h3><p>Good for:</p><ul><li>Validation</li><li>Transformation</li><li>Business rules</li><li>Formatting</li><li>Mapping</li></ul><h3>Component tests</h3><p>Good for:</p><ul><li>Rendering</li><li>Interactions</li><li>Loading states</li><li>Error states</li></ul><h3>E2E tests</h3><p>Good for:</p><ul><li>Critical workflows</li><li>Cross-component behavior</li><li>Backend integration</li></ul><p>You don’t need 100% coverage just because you’re refactoring.</p><p>You need <strong>confidence around behavior that matters</strong>.</p><h3>17. Small PRs Are Part of the Architecture</h3><p>I would much rather review:</p><h3>PR #1</h3><pre>Extract ProductFilters</pre><h3>PR #2</h3><pre>Extract ProductTable</pre><h3>PR #3</h3><pre>Extract product-fetching behavior</pre><p>than:</p><pre>Refactor ProductManagement</pre><pre>4,000 lines changed</pre><p>Small PRs provide:</p><ul><li>Easier review</li><li>Easier rollback</li><li>Smaller regression surface</li><li>Better Git history</li><li>Easier debugging</li><li>Fewer merge conflicts</li></ul><p>For a Tech Lead, this isn’t just a code-quality practice.</p><p>It’s a <strong>team scalability practice</strong>.</p><h3>18. Don’t Mix Refactoring With Everything Else</h3><p>Avoid combining:</p><pre>React upgrade<br>      +<br>State migration<br>      +<br>API changes<br>      +<br>UI redesign<br>      +<br>CSS migration<br>      +<br>Component refactoring</pre><p>in one change.</p><p>If production breaks, you’ve created a debugging nightmare.</p><p>Instead:</p><pre>Refactor<br>   ↓<br>Stabilize<br>   ↓<br>Measure<br>   ↓<br>Optimize</pre><p>One major change at a time.</p><h3>19. Feature Flags for High-Risk Refactoring</h3><p>For critical workflows, feature flags can provide another safety mechanism.</p><pre>return useNewProductExperience<br>  ? &lt;NewProductManagement /&gt;<br>  : &lt;LegacyProductManagement /&gt;;</pre><p>You can then gradually expose the new implementation:</p><pre>1%<br> ↓<br>5%<br> ↓<br>25%<br> ↓<br>50%<br> ↓<br>100%</pre><p>This is especially useful for:</p><ul><li>High-traffic screens</li><li>Revenue-critical workflows</li><li>Enterprise applications</li><li>Large micro-frontends</li><li>High-risk architectural changes</li></ul><p>The goal isn’t to keep two implementations forever.</p><p>The flag is temporary.</p><p>Once confidence is established, remove the legacy path.</p><h3>20. Before and After</h3><h3>Before</h3><pre>function ProductManagement() {<br>  const [products, setProducts] = useState([]);<br>  const [filter, setFilter] = useState(&quot;&quot;);<br>  const [selected, setSelected] = useState([]);<br>  const [loading, setLoading] = useState(false);<br>  const [showDialog, setShowDialog] = useState(false);<br><br>  useEffect(() =&gt; {<br>    // Fetch products<br>  }, []);<br>  const filteredProducts = products.filter(...);<br>  const handleSelect = (...) =&gt; {<br>    // Selection logic<br>  };<br>  const handleExport = (...) =&gt; {<br>    // Export logic<br>  };<br>  return (<br>    &lt;&gt;<br>      {/* hundreds of lines of JSX */}<br>    &lt;/&gt;<br>  );<br>}</pre><p>The problem isn’t that this code is necessarily “wrong.”</p><p>The problem is that the component has become responsible for too many things.</p><h3>After</h3><pre>function ProductManagement() {<br>  const {<br>    products,<br>    loading<br>  } = useProducts();<br><br>const {<br>    filter,<br>    setFilter,<br>    filteredProducts<br>  } = useProductFilters(products);<br>  const {<br>    selected,<br>    handleSelect<br>  } = useProductSelection();<br>  return (<br>    &lt;ProductPage&gt;<br>      &lt;ProductFilters<br>        value={filter}<br>        onChange={setFilter}<br>      /&gt;<br>      &lt;ProductTable<br>        products={filteredProducts}<br>        selected={selected}<br>        onSelect={handleSelect}<br>        loading={loading}<br>      /&gt;<br>      &lt;ProductActions<br>        products={selected}<br>      /&gt;<br>    &lt;/ProductPage&gt;<br>  );<br>}</pre><p>Now the page mostly describes <strong>composition</strong>.</p><p>That’s a much healthier responsibility for a page-level component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W5Kqk-YmYyrYpwtq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*-Us0Uy5yAKcMgyVV" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DaMJF7K0obXau1xp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*BcGeeHziVIJddmUQ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eYiGd040dZBvoOfr" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4CB3eMW9FOSu2ZkP" /></figure><h3>21. Performance: Smaller Doesn’t Automatically Mean Faster</h3><p>This is another misconception worth calling out.</p><p>Breaking:</p><pre>1 large component</pre><p>into:</p><pre>10 smaller components</pre><p>doesn’t automatically improve performance.</p><p>You can accidentally introduce:</p><ul><li>unnecessary renders</li><li>duplicated calculations</li><li>excessive context updates</li><li>duplicate API requests</li><li>unnecessary useMemo</li><li>unnecessary useCallback</li><li>prop churn</li></ul><p>Architecture and performance are related.</p><p>But they are not the same problem.</p><p><strong>Measure before optimizing.</strong></p><p>Use profiling and production telemetry to determine whether performance actually improved.</p><h3>22. Measure the Refactor by Change Cost</h3><p>Don’t define success as:</p><pre>1,200 lines → 300 lines</pre><p>That’s useful, but it’s not the objective.</p><p>Look at:</p><p>MetricBeforeAfterCognitive complexityHighLowerCouplingHighLowerTestabilityLowHigherAPI duplicationXYProduction errorsXYRender performanceX msY msRegression rateXYChange effortHighLower</p><p>The real goal is:</p><pre>Complexity       ↓<br>Coupling         ↓<br>Regression risk  ↓<br>Testability      ↑<br>Maintainability  ↑<br>Developer speed  ↑</pre><p>The most valuable result is not fewer lines.</p><p>It’s <strong>lower change cost</strong>.</p><h3>23. When Should You NOT Refactor?</h3><p>This is one of the most important lessons from working on production systems.</p><p>Not every large component needs to be refactored.</p><p>Don’t do it simply because:</p><ul><li>The file is long</li><li>Someone prefers smaller files</li><li>A new architecture is fashionable</li><li>You want to introduce another library</li><li>The code doesn’t match your personal style</li></ul><p>If the component is:</p><ul><li>stable</li><li>well tested</li><li>rarely changed</li><li>low risk</li><li>isolated</li></ul><p>then a large refactor may introduce more risk than value.</p><p>Ask:</p><pre>Expected future benefit<br>          │<br>          ▼<br>   Is it worth the<br>    refactoring risk?<br>          │<br>       Yes / No</pre><p>That’s an engineering decision.</p><p>Not a formatting decision.</p><h3>24. The 10+ Year Lesson</h3><p>After years of frontend development, I’ve learned that the hardest part of refactoring isn’t writing the new implementation.</p><p>It’s understanding the <strong>existing behavior</strong> well enough to change the implementation without changing what users depend on.</p><p>Production code contains things that aren’t always obvious from the component:</p><ul><li>Business assumptions</li><li>Permission rules</li><li>Legacy integrations</li><li>API quirks</li><li>Analytics dependencies</li><li>Browser-specific workarounds</li><li>Hidden consumers</li><li>Historical production fixes</li><li>Expectations from other teams</li></ul><p>That’s why a rewrite can be much riskier than incremental decomposition.</p><p>The safest mindset is:</p><blockquote><strong><em>Preserve behavior first. Improve structure second. Optimize third.</em></strong></blockquote><h3>25. My Production Refactoring Checklist</h3><h3>Before the refactor</h3><ul><li>Identify all consumers</li><li>Understand current behavior</li><li>Map responsibilities</li><li>Identify state ownership</li><li>Identify API dependencies</li><li>Identify critical workflows</li><li>Review existing tests</li><li>Check production metrics</li></ul><h3>During the refactor</h3><ul><li>Keep public contracts stable</li><li>Extract pure functions first</li><li>Extract React-specific behavior</li><li>Keep state close to consumers</li><li>Avoid unnecessary abstractions</li><li>Avoid unrelated changes</li><li>Watch for duplicate API calls</li><li>Keep PRs small</li></ul><h3>Before merging</h3><ul><li>TypeScript passes</li><li>Unit tests pass</li><li>Component tests pass</li><li>E2E tests pass</li><li>Build passes</li><li>No duplicate requests</li><li>No unexpected rendering regressions</li></ul><h3>After deployment</h3><ul><li>Monitor errors</li><li>Monitor API behavior</li><li>Monitor performance</li><li>Compare production metrics</li><li>Watch critical user workflows</li><li>Remove obsolete code once confidence is established</li></ul><h3>Final Thought</h3><p>Large React components aren’t necessarily the enemy.</p><p><strong>Uncontrolled complexity is.</strong></p><p>The best refactoring strategy isn’t:</p><pre>Big Component<br>      ↓<br>Rewrite Everything</pre><p>It’s:</p><pre>Big Component<br>      ↓<br>Understand<br>      ↓<br>Protect<br>      ↓<br>Extract<br>      ↓<br>Test<br>      ↓<br>Measure<br>      ↓<br>Repeat<br>      ↓<br>Simpler Architecture</pre><p>The objective isn’t to create more files.</p><p>It’s to make <strong>change safer</strong>.</p><p>And after 10+ years of frontend engineering, that’s one of the most valuable characteristics a production codebase can have:</p><p><strong>Better code.<br>Safer releases.<br>Faster development.<br>Lower regression risk.</strong></p><p>Because good frontend architecture isn’t about how elegant the code looks on the day you write it.</p><p>It’s about <strong>how safely the next developer can change it six months later.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c29cac98d03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux in 2026: Do We Still Need Redux?]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/redux-in-2026-do-we-still-need-redux-ad52364bce6d?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad52364bce6d</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 17:07:38 GMT</pubDate>
            <atom:updated>2026-08-29T17:07:38.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*96_Nh571fgDmQhkiKWMmNw.png" /></figure><h3>After 10+ years of building React applications, the question is no longer “Redux or no Redux?” — it is “Who owns this state?”</h3><h3>The question has changed</h3><p>There was a time when building a serious React application almost automatically meant introducing Redux.</p><p>The conversation was simple:</p><pre>React application<br>       ↓<br>Complex state<br>       ↓<br>Redux</pre><p>Today, that decision is no longer that simple.</p><p>Modern React applications have many ways to manage state:</p><pre>useState<br>useReducer<br>Context<br>URL State<br>Browser Storage<br>Query Cache<br>RTK Query<br>Redux Toolkit<br>Server Components</pre><p>And that’s a good thing.</p><p>But it also creates a new architectural problem.</p><p>We now have <strong>more choices</strong>, but choosing the wrong place for state can create just as much technical debt as choosing the wrong library.</p><p>After more than a decade of working with frontend systems, I’ve learned that the most important question isn’t:</p><blockquote><strong><em>“Should we use Redux?”</em></strong></blockquote><p>It’s:</p><blockquote><strong><em>“Where should this state live?”</em></strong></blockquote><p>That single question can preve nt a surprising amount of frontend complexity.</p><p>Use a visual showing:</p><pre>                  APPLICATION STATE<br>                           │<br>        ┌──────────────────┼──────────────────┐<br>        │                  │                  │<br>        ▼                  ▼                  ▼<br>     UI State          Server State       Global State<br>        │                  │                  │<br>        ▼                  ▼                  ▼<br>    useState          Query Cache       Redux / Context<br>        │                  │                  │<br>        ▼                  ▼                  ▼<br>    Component           API/Data          Features</pre><p>The important concept is:</p><blockquote><strong><em>Different state has different owners.</em></strong></blockquote><h3>1. Redux Isn’t Dead</h3><p>Let’s get the obvious question out of the way.</p><h3>Do we still need Redux in 2026?</h3><p><strong>Yes.</strong></p><p>But I would no longer recommend Redux simply because:</p><ul><li>the application is large</li><li>the team is large</li><li>you’re using React</li><li>the application has many components</li><li>the application uses TypeScript</li><li>“enterprise applications use Redux”</li></ul><p>Those aren’t sufficient reasons.</p><p>Redux is still extremely useful when an application has:</p><ul><li>complex client-side state</li><li>cross-feature state</li><li>complex workflows</li><li>predictable state transitions</li><li>centralized business rules</li><li>offline-first requirements</li><li>rich editors</li><li>complex dashboards</li><li>coordinated interactions across independent components</li></ul><p>But if the problem is simply:</p><pre>const [isOpen, setIsOpen] = useState(false);</pre><p>Redux is probably not the answer.</p><p>And that distinction becomes extremely important at scale.</p><h3>2. The State Management Landscape Has Changed</h3><p>The frontend ecosystem has evolved significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xxnQ_QhBQFZnaf9b" /></figure><p>A modern application might look like this:</p><pre>                         STATE<br>                           │<br>          ┌────────────────┼────────────────┐<br>          │                │                │<br>          ▼                ▼                ▼<br>       Local             URL             Server<br>          │                │                │<br>          ▼                ▼                ▼<br>      useState          Router          Query Cache<br>      useReducer       Search Params    RTK Query<br>          │                │                │<br>          └────────────────┼────────────────┘<br>                           │<br>                           ▼<br>                    Global Client State<br>                           │<br>                           ▼<br>                    Redux / Context</pre><p>The mistake is assuming that every box belongs in Redux.</p><p>It doesn’t.</p><h3>3. The First Question I Ask: Who Owns This State?</h3><p>This is probably the biggest shift in my thinking after years of frontend development.</p><p>Instead of asking:</p><blockquote><em>“Which library should manage this?”</em></blockquote><p>I ask:</p><blockquote><strong><em>“Who owns this state?”</em></strong></blockquote><p>For example:</p><h3>Modal</h3><pre>isModalOpen<br><br>Owner:<br><br>Component</pre><h3>Search filters</h3><pre>?page=2&amp;status=active<br><br>Owner:<br><br>URL</pre><h3>Products from an API</h3><pre>GET /products<br><br>Owner:<br>Server</pre><h3>Shopping cart</h3><pre>cartItems<br><br>Potential owner:<br>Global client state</pre><h3>Multi-step checkout</h3><pre>cart<br> ↓<br>shipping<br> ↓<br>payment<br> ↓<br>confirmation<br><br>Potential owner:<br>Global workflow state</pre><p>This sounds simple.</p><p>But in large applications, getting this wrong can create months of maintenance problems.</p><h3>4. What Redux Was Originally Very Good At</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*ZEgK973xxCFuIejy" /></figure><p>Redux solved a very real problem.</p><p>Imagine:</p><pre>                    App<br>                     │<br>             ┌───────┴───────┐<br>             │               │<br>          Header          Dashboard<br>             │               │<br>           User          ┌────┴────┐<br>                        │         │<br>                      Chart      Table</pre><p>Without centralized state, you may end up with:</p><pre>App<br> ↓<br>Dashboard<br> ↓<br>Chart<br> ↓<br>Toolbar<br> ↓<br>Filter</pre><p>passing:</p><pre>state<br>callbacks<br>handlers<br>configuration</pre><p>through multiple levels.</p><p>Redux provided a centralized model:</p><pre>                 Redux Store<br>               /     |      \<br>              /      |       \<br>             ▼       ▼        ▼<br>         Header   Dashboard  Sidebar</pre><p>And, more importantly, it gave developers predictable state transitions.</p><h3>5. Redux’s Core Strength: Explicit Data Flow</h3><p>The traditional Redux flow is still one of its biggest strengths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*U0mxEeHBW4dflxCM" /></figure><pre>┌───────────┐<br>│ Component │<br>└─────┬─────┘<br>      │<br>      │ dispatch(action)<br>      ▼<br>┌───────────┐<br>│  Action   │<br>└─────┬─────┘<br>      │<br>      ▼<br>┌───────────┐<br>│  Reducer  │<br>└─────┬─────┘<br>      │<br>      │ new state<br>      ▼<br>┌───────────┐<br>│   Store   │<br>└─────┬─────┘<br>      │<br>      │ notify<br>      ▼<br>┌───────────┐<br>│ Selector  │<br>└─────┬─────┘<br>      │<br>      ▼<br>┌───────────┐<br>│ Component │<br>└───────────┘</pre><p>This gives us something valuable:</p><p><strong>The state transition is explicit.</strong></p><p>That makes complex applications easier to debug.</p><p>But there is a catch.</p><p>Explicit architecture can still become <strong>too much architecture</strong>.</p><h3>6. The Problem I Have Seen Most Often: Redux Becomes a Dumping Ground</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YJw1rTcZ0h_9_DtC" /></figure><p>This is where things usually start going wrong.</p><p>The application begins with:</p><pre>auth<br>user<br>permissions<br>cart</pre><p>Then:</p><pre>products<br>orders<br>notifications</pre><p>Then:</p><pre>filters<br>search<br>tabs<br>modals<br>forms</pre><p>Then:</p><pre>hoveredRow<br>selectedTab<br>expandedPanel<br>temporaryValue<br>tooltip</pre><p>Eventually:</p><pre>Redux Store<br>│<br>├── auth<br>├── user<br>├── permissions<br>├── products<br>├── orders<br>├── cart<br>├── filters<br>├── search<br>├── forms<br>├── modals<br>├── tabs<br>├── dashboard<br>├── notifications<br>├── temporaryState<br>└── randomFeatureState</pre><p>At this point, Redux has stopped being a carefully designed global state layer.</p><p>It has become:</p><blockquote><strong><em>The place where anything goes when a developer doesn’t know where else to put it.</em></strong></blockquote><h3>⚠️ Production Issue #1: Globalizing Temporary UI State</h3><p>I’ve seen this happen repeatedly.</p><p>A developer has:</p><pre>const [isOpen, setIsOpen] = useState(false);</pre><p>Then another component needs to know whether the panel is open.</p><p>Instead of reconsidering the component boundary, the team creates:</p><pre>filterSlice<br><br>Now:<br><br>Header<br>   │<br>   │ dispatch(openFilter())<br>   ▼<br>Redux<br>   │<br>   ▼<br>FilterPanel</pre><p>Technically:</p><p><strong>It works.</strong></p><p>Architecturally:</p><p><strong>We just turned a local UI concern into application-wide state.</strong></p><p>Now we have:</p><pre>Action<br>Reducer<br>Selector<br>Dispatch<br>Subscription<br>Tests</pre><p>for a boolean.</p><p>That’s unnecessary complexity.</p><h3>7. The Redux Tax</h3><p>This is something you understand much better after maintaining applications for years.</p><p>Consider:</p><pre>const [isOpen, setIsOpen] = useState(false);</pre><p>The mental model is:</p><pre>state<br>+<br>setter</pre><p>Now compare that with global state:</p><pre>Component<br> ↓<br>dispatch<br> ↓<br>action<br> ↓<br>reducer<br> ↓<br>store<br> ↓<br>selector<br> ↓<br>component</pre><p>The second architecture isn’t bad.</p><p>It is simply <strong>more expensive</strong>.</p><p>That additional complexity is justified when it solves a real problem.</p><p>It isn’t justified merely because Redux exists.</p><p>I think of this as:</p><blockquote><strong><em>The Redux Tax.</em></strong></blockquote><h3>8. Production Issue #2: Server State Gets Treated Like Client State</h3><p>This is another problem I’ve encountered in large applications.</p><p>Imagine:</p><pre>GET /api/products</pre><p>The response is stored in Redux.</p><p>Then the team adds:</p><pre>loading<br>error<br>lastFetched<br>refresh<br>invalidate<br>retry<br>cache</pre><p>Eventually:</p><pre>productsSlice</pre><p>starts looking like a homemade query engine.</p><p>And the question becomes:</p><blockquote><strong><em>Why are we building a server-state management system inside our client-state store?</em></strong></blockquote><h3>9. Server State and Client State Are Different</h3><p>This distinction is fundamental.</p><h3>Server state</h3><pre>Users<br>Products<br>Orders<br>Invoices<br>Reports</pre><p>Characteristics:</p><pre>Remote<br>Async<br>Cacheable<br>Stale<br>Refetchable<br>Invalidatable<br>Shared</pre><h3>Client state</h3><pre>Modal<br>Selected tab<br>Sidebar state<br>Draft values<br>Wizard progress<br>UI preferences</pre><p>Characteristics:</p><pre>Browser-owned<br>Interactive<br>Local or global<br>Usually synchronous</pre><p>These are fundamentally different problems.</p><h3>🔄 Server State Sequence Diagram</h3><p>A query/cache architecture looks more like:</p><pre>┌───────────┐<br>│ Component │<br>└─────┬─────┘<br>      │<br>      │ useQuery()<br>      ▼<br>┌───────────┐<br>│   Cache   │<br>└─────┬─────┘<br>      │<br>      │ cache miss / stale<br>      ▼<br>┌───────────┐<br>│    API    │<br>└─────┬─────┘<br>      │<br>      │ response<br>      ▼<br>┌───────────┐<br>│   Cache   │<br>└─────┬─────┘<br>      │<br>      │ data<br>      ▼<br>┌───────────┐<br>│ Component │<br>└───────────┘</pre><p>This is fundamentally different from:</p><pre>dispatch<br> ↓<br>reducer<br> ↓<br>global state</pre><h3>10. Redux Toolkit Changed the Conversation</h3><p>It’s also important not to talk about Redux as if it is still the Redux of the early React ecosystem.</p><p>Redux Toolkit significantly improved the developer experience.</p><p>Instead of manually wiring everything around traditional Redux patterns, teams can use:</p><pre>Slices<br>Immer-based updates<br>Typed hooks<br>Middleware<br>Selectors<br>RTK Query</pre><p>And RTK Query is especially important because it allows Redux-based applications to manage server-state concerns much more effectively.</p><p>A modern Redux architecture can therefore look like:</p><pre>Redux<br>│<br>├── Client State<br>│   ├── auth<br>│   ├── preferences<br>│   └── workflows<br>│<br>└── RTK Query<br>    ├── users<br>    ├── products<br>    ├── orders<br>    └── reports</pre><p>That’s very different from:</p><pre>Redux<br>└── Everything</pre><h3>11. Production Issue #3: Too Many Actions</h3><p>Another problem that appears over time is action explosion.</p><p>Initially:</p><pre>login<br>logout<br>addToCart<br>removeFromCart</pre><p>Then:</p><pre>setTab<br>setActiveTab<br>setCurrentTab</pre><p>Then:</p><pre>setFilter<br>updateFilter<br>clearFilter<br>resetFilter</pre><p>Then:</p><pre>setLoading<br>setTableLoading<br>setDashboardLoading</pre><p>Now a developer opening the code has to figure out:</p><pre>Which action?<br>Which slice?<br>Which reducer?<br>Which selector?<br>Which state?</pre><p>The problem isn’t Redux.</p><p>The problem is that the global state model no longer represents meaningful business concepts.</p><h3>12. Production Issue #4: Duplicate State</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3taZtzys2K8WMTkB" /></figure><p>This is one of the most dangerous patterns.</p><p>Consider:</p><pre>const user = useSelector(selectUser);<br><br>const [localUser, setLocalUser] = useState(user);</pre><p>Now we have:</p><pre>Redux User<br>     │<br>     └───────┐<br>             ▼<br>        Local User</pre><p>There are now two sources of truth.</p><p>Eventually someone writes:</p><pre>useEffect(() =&gt; {<br>  setLocalUser(user);<br>}, [user]);</pre><p>Now we have created a synchronization mechanism to synchronize duplicated state.</p><p>This is exactly the type of architecture that becomes difficult to reason about.</p><h3>13. Don’t Store What You Can Derive</h3><p>This principle applies to both React and Redux.</p><p>Bad:</p><pre>const [total, setTotal] = useState(0);<br><br>useEffect(() =&gt; {<br>  setTotal(<br>    items.reduce(<br>      (sum, item) =&gt; sum + item.price,<br>      0<br>    )<br>  );<br>}, [items]);</pre><p>Better:</p><pre>const total = items.reduce(<br>  (sum, item) =&gt; sum + item.price,<br>  0<br>);</pre><p>The same idea applies to Redux.</p><p>Don’t store:</p><pre>Source State<br>+<br>Derived State</pre><p>when you can simply calculate:</p><pre>Source State<br>     ↓<br>Selector<br>     ↓<br>Derived Value</pre><p>Every synchronization relationship you remove is one less thing that can break.</p><h3>14. Production Issue #5: Redux Coupling Spreads Everywhere</h3><p>Another issue I have faced is making every component Redux-aware.</p><p>For example:</p><pre>const UserCard = () =&gt; {<br>  const user = useSelector(selectUser);<br>  const dispatch = useDispatch();<br>  ...<br>};</pre><p>Now UserCard depends directly on Redux.</p><p>That affects:</p><ul><li>testing</li><li>Storybook</li><li>reuse</li><li>composition</li><li>isolation</li></ul><p>Instead, a component can often remain simple:</p><pre>const UserCard = ({<br>  user,<br>  onUpdate<br>}) =&gt; {<br>  ...<br>};</pre><p>Then connect Redux at the feature boundary:</p><pre>Redux<br>   ↓<br>Feature Container<br>   ↓<br>Presentational Component</pre><p>This keeps global-state knowledge closer to where it belongs.</p><h3>15. Production Issue #6: Testing Becomes Heavier</h3><p>Compare:</p><pre>render(<br>  &lt;UserCard user={user} /&gt;<br>);<br><br>with:<br><br>render(<br>  &lt;Provider store={store}&gt;<br>    &lt;UserCard /&gt;<br>  &lt;/Provider&gt;<br>);</pre><p>The second isn’t necessarily wrong.</p><p>But the test now depends on:</p><pre>Store<br>Reducers<br>Middleware<br>Initial State<br>Provider<br>Selectors</pre><p>Again:</p><p><strong>One component isn’t a problem.</strong></p><p>But hundreds of components create architectural consequences.</p><p>This is why I increasingly care about <strong>dependency boundaries</strong>.</p><h3>16. Production Issue #7: Selectors Become a Second Application</h3><p>Selectors are powerful.</p><p>But I’ve seen large Redux applications accumulate:</p><pre>selectUser<br>selectUserPermissions<br>selectIsAdmin<br>selectCanEdit<br>selectCanDelete<br>selectVisibleUsers<br>selectFilteredUsers<br>selectSortedUsers<br>selectDashboardData<br>selectChartData</pre><p>Soon, understanding a feature requires understanding:</p><pre>Component<br> ↓<br>Selector<br> ↓<br>Selector dependency<br> ↓<br>Another selector<br> ↓<br>Redux state</pre><p>Selectors should help model state.</p><p>They shouldn’t become a second place where half the application’s business logic is hidden.</p><h3>17. Production Issue #8: “Everything Depends on Redux”</h3><p>This is the architectural smell I watch carefully.</p><p>If every feature imports:</p><pre>useSelector<br>useDispatch</pre><p>then Redux has become part of the application’s component API.</p><p>Instead, I prefer:</p><pre>Application<br>     │<br>     ▼<br>Feature Boundary<br>     │<br>     ▼<br>State Mapping<br>     │<br>     ▼<br>Reusable Components</pre><p>This gives us a cleaner separation.</p><h3>18. State Ownership Decision Tree</h3><p>This is the decision framework I use today.</p><pre>               What kind of state is this?<br>                          │<br>                          ▼<br>                  Is the server the owner?<br>                     /          \<br>                   YES           NO<br>                    │             │<br>                    ▼             ▼<br>               Query Cache     Is it URL state?<br>                                /          \<br>                              YES           NO<br>                               │             │<br>                               ▼             ▼<br>                              URL      Is it local UI?<br>                                          /    \<br>                                        YES     NO<br>                                         │       │<br>                                         ▼       ▼<br>                                      Local    Does it cross<br>                                      State    feature boundaries?<br>                                                   /      \<br>                                                 NO       YES<br>                                                  │         │<br>                                                  ▼         ▼<br>                                             Local/Context Redux</pre><p>This is the biggest change I’d recommend to teams.</p><p>Don’t start with:</p><pre>&quot;Should we use Redux?&quot;</pre><p>Start with:</p><pre>&quot;What kind of state is this?&quot;</pre><h3>19. When I Would Still Choose Redux</h3><p>There are still many situations where I would choose Redux without hesitation.</p><h3>Complex workflows</h3><p>For example:</p><pre>Checkout<br>   ↓<br>Address<br>   ↓<br>Shipping<br>   ↓<br>Payment<br>   ↓<br>Confirmation</pre><p>If multiple independent components participate in the workflow, centralized state can be valuable.</p><h3>Cross-feature state</h3><p>For example:</p><pre>Cart<br>  ↕<br>Product<br>  ↕<br>Checkout<br>  ↕<br>Payment</pre><p>If several features need to coordinate around the same client-owned state, Redux can provide a useful boundary.</p><h3>Rich dashboards</h3><p>Consider:</p><pre>Dashboard<br>│<br>├── Filters<br>├── Charts<br>├── Tables<br>├── Maps<br>├── Drilldowns<br>├── Selected entities<br>└── Cross-widget interactions</pre><p>If changing one part of the dashboard affects several independent components, structured global state can make the data flow much easier to reason about.</p><h3>Complex editors</h3><p>Think:</p><pre>Document<br> ├── Sections<br> ├── Blocks<br> ├── Selection<br> ├── History<br> ├── Undo<br> ├── Redo<br> └── Collaboration</pre><p>This is a very different problem from:</p><pre>const [isOpen, setIsOpen] = useState(false);</pre><p>Redux or a reducer-based state architecture can be a very strong fit here.</p><h3>20. A Practical Example: E-commerce</h3><p>Imagine an e-commerce product page.</p><p>We have:</p><pre>product<br>reviews<br>inventory<br>recommendations<br>selectedSize<br>selectedColor<br>quantity<br>wishlist<br>cart</pre><p>Should all of this be Redux?</p><p>No.</p><p>I’d separate it.</p><pre>SERVER STATE<br>│<br>├── product<br>├── reviews<br>├── inventory<br>└── recommendations<br><br>LOCAL UI STATE<br>│<br>├── selectedSize<br>├── selectedColor<br>└── quantity<br><br>GLOBAL CLIENT STATE<br>│<br>├── cart<br>├── wishlist<br>└── session/preferences</pre><p>Now the architecture communicates intent.</p><p>A developer can understand why each piece of state exists where it does.</p><p>That’s more valuable than simply having fewer libraries.</p><h3>21. A Practical Example: Enterprise Dashboard</h3><p>Now consider an enterprise analytics dashboard:</p><pre>Dashboard<br>│<br>├── Plant<br>├── Date Range<br>├── Metrics<br>├── Charts<br>├── Map<br>├── Tables<br>├── Filters<br>└── Drill-down</pre><p>Suppose:</p><pre>Selected Plant<br>      │<br>      ├──────────────┐<br>      ▼              ▼<br>    Chart           Table<br>      │              │<br>      ▼              ▼<br>   Metrics          Map</pre><p>This is a stronger Redux candidate.</p><p>But:</p><pre>tooltipVisible<br>hoveredPoint<br>modalOpen<br>expandedRow</pre><p>may still belong locally.</p><p>This distinction is where senior frontend architecture becomes important.</p><h3>22. Redux vs Context</h3><p>I don’t see this as:</p><pre>Redux &gt; Context</pre><p>or:</p><pre>Context &gt; Redux</pre><p>They solve different problems.</p><h3>Context</h3><p>Good candidates:</p><pre>Theme<br>Locale<br>Authentication context<br>Configuration<br>Dependency injection<br>Small application-wide values</pre><h3>Redux</h3><p>Good candidates:</p><pre>Complex client state<br>Cross-feature workflows<br>Explicit transitions<br>Selectors<br>Middleware<br>Debugging<br>Structured global state<br>Complex business rules</pre><p>Context is not automatically a replacement for Redux.</p><p>A massive Context provider containing frequently changing state can create its own architectural problems.</p><p>Again:</p><blockquote><strong><em>The state model matters more than the library name.</em></strong></blockquote><h3>23. Redux vs Local State</h3><p>For:</p><pre>const [isOpen, setIsOpen] = useState(false);</pre><p>I’d choose local state.</p><p>For:</p><pre>Complex checkout<br>Multiple independent components<br>Shared workflow<br>Predictable transitions<br>Business rules</pre><p>Redux becomes much more attractive.</p><p>The mistake is treating both problems as if they have the same complexity.</p><p>They don’t.</p><h3>24. What About Next.js?</h3><p>Modern Next.js introduces another important architectural boundary:</p><pre>Server<br>   │<br>   ▼<br>Data Fetching<br>   │<br>   ▼<br>Server Component<br>   │<br>   ▼<br>Client Boundary<br>   │<br>   ▼<br>Interactive State</pre><p>One of the mistakes I see is turning a large section of the application into a Client Component because one small part needs interaction.</p><p>For example:</p><pre>&quot;use client&quot;;</pre><p>is added high in the component tree because a single button needs:</p><pre>useState()</pre><p>Now the boundary has moved much further than necessary.</p><p>I prefer:</p><pre>Server Component<br>       │<br>       ├── Server Data<br>       │<br>       └── Client Component<br>               │<br>               ├── Local State<br>               └── Redux if required</pre><p>The same principle applies:</p><blockquote><strong><em>Don’t cross an architectural boundary just because one small part needs to.</em></strong></blockquote><h3>25. Redux Anti-Pattern: The Giant Store</h3><p>A mature application can sometimes end up with:</p><pre>store/<br>│<br>├── authSlice<br>├── userSlice<br>├── productSlice<br>├── orderSlice<br>├── cartSlice<br>├── dashboardSlice<br>├── modalSlice<br>├── filterSlice<br>├── formSlice<br>├── notificationSlice<br>├── tableSlice<br>├── searchSlice<br>└── temporarySlice</pre><p>This is a warning sign.</p><p>Not because having many slices is inherently bad.</p><p>But because it often indicates that Redux has become the default destination for every state problem.</p><h3>26. A Healthier Redux Architecture</h3><p>For a large application, I’d rather see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FB59e9bgJmTw2gFs" /></figure><pre>src/<br>│<br>├── app/<br>│   ├── providers/<br>│   ├── routes/<br>│   └── store/<br>│<br>├── features/<br>│   │<br>│   ├── auth/<br>│   │   ├── components/<br>│   │   ├── state/<br>│   │   ├── services/<br>│   │   └── types/<br>│   │<br>│   ├── checkout/<br>│   │   ├── components/<br>│   │   ├── state/<br>│   │   ├── services/<br>│   │   └── types/<br>│   │<br>│   └── dashboard/<br>│       ├── components/<br>│       ├── state/<br>│       ├── services/<br>│       └── types/<br>│<br>└── shared/<br>    ├── ui/<br>    ├── hooks/<br>    └── lib/</pre><p>The important thing isn’t copying this exact folder structure.</p><p>The important thing is:</p><blockquote><strong><em>Ownership should be obvious.</em></strong></blockquote><h3>27. Production Issue #9: Global State Becomes Architectural Gravity</h3><p>This is one of the hardest problems to reverse.</p><p>Adding something to Redux is easy.</p><p>Removing it later can be extremely difficult.</p><p>Imagine:</p><pre>Feature A<br>     │<br>     ▼<br>   Redux<br>   ▲  ▲<br>   │  │<br>Feature B  Feature C</pre><p>Now three features depend on the same state.</p><p>Removing that state means understanding:</p><pre>Who reads it?<br>Who writes it?<br>Who derives from it?<br>Who dispatches its actions?<br>Which tests depend on it?<br>Which workflows depend on it?</pre><p>This is why I treat global state as:</p><blockquote><strong><em>A commitment, not a convenience.</em></strong></blockquote><h3>28. Don’t Globalize State “Just in Case”</h3><p>One of the most common arguments is:</p><blockquote><em>“Another component might need this later.”</em></blockquote><p>That’s not a good reason to globalize state.</p><p>Instead:</p><pre>Start local<br>     ↓<br>Actual reuse appears<br>     ↓<br>Understand dependency<br>     ↓<br>Move state to appropriate boundary</pre><p>Don’t design architecture around hypothetical requirements.</p><p>Architecture should respond to real relationships.</p><h3>29. The Hidden Cost: Change Becomes More Expensive</h3><p>This is the real issue.</p><p>A healthy application looks like:</p><pre>Feature Request<br>      ↓<br>Small Change<br>      ↓<br>Test<br>      ↓<br>Deploy</pre><p>A highly coupled application looks like:</p><pre>Feature Request<br>      ↓<br>Find Redux state<br>      ↓<br>Find selectors<br>      ↓<br>Find actions<br>      ↓<br>Find dependent components<br>      ↓<br>Check middleware<br>      ↓<br>Check API synchronization<br>      ↓<br>Change code<br>      ↓<br>Something breaks<br>      ↓<br>Add workaround<br>      ↓<br>Add another test<br>      ↓<br>Deploy</pre><p>This is technical debt.</p><p>Not because the code is ugly.</p><p>Because:</p><blockquote><strong><em>Change has become expensive.</em></strong></blockquote><h3>30. The Redux Migration Problem</h3><p>Suppose you inherit an application with:</p><pre>10+ years of Redux usage<br>Hundreds of slices<br>Thousands of actions<br>Server data in Redux<br>UI state in Redux<br>Legacy reducers<br>Mixed patterns</pre><p>I would <strong>not</strong> recommend:</p><blockquote><em>“Let’s remove Redux.”</em></blockquote><p>And I definitely wouldn’t recommend:</p><blockquote><em>“Let’s rewrite the application.”</em></blockquote><p>Instead, migrate incrementally.</p><h3>Step 1 — Inventory the store</h3><p>Categorize every major state branch:</p><pre>Client State<br>Server State<br>UI State<br>Derived State<br>Persistent State<br>Legacy State</pre><h3>Step 2 — Find unnecessary global state</h3><p>Look for:</p><pre>Modal state<br>Temporary state<br>Hover state<br>Form state<br>Duplicated state<br>Derived state</pre><h3>Step 3 — Move server state</h3><p>Identify API-owned data.</p><p>Move appropriate resources toward:</p><pre>RTK Query<br>Query cache<br>Framework data fetching</pre><p>depending on the application.</p><h3>Step 4 — Reduce coupling</h3><p>Instead of:</p><pre>Every component → Redux</pre><p>move toward:</p><pre>Feature → Redux<br>Feature → Components</pre><h3>Step 5 — Delete dead state</h3><p>This is often the most valuable step.</p><p>Don’t simply create the new architecture.</p><p>Remove the old one.</p><h3>31. The Architecture I Would Start With Today</h3><p>If I were starting a large React application today, my mental model would be:</p><pre>                         APPLICATION<br>                              │<br>          ┌───────────────────┼───────────────────┐<br>          │                   │                   │<br>          ▼                   ▼                   ▼<br>       UI State           URL State          Server State<br>          │                   │                   │<br>          ▼                   ▼                   ▼<br>      useState              Router           Query Cache<br>      useReducer           Search Params      RTK Query<br>          │                   │                   │<br>          └───────────────────┼───────────────────┘<br>                              │<br>                              ▼<br>                     Global Client State<br>                              │<br>                              ▼<br>                           Redux</pre><p>Redux is no longer:</p><pre>The state manager.</pre><p>It becomes:</p><blockquote><strong><em>One carefully chosen state boundary in the application.</em></strong></blockquote><p>That’s a much healthier architecture.</p><h3>32. My Redux Decision Matrix</h3><p>ProblemFirst ChoiceModal stateLocal stateTooltipLocal stateHover stateLocal stateSelected tabLocal stateInput stateLocal/form stateSearch/filter that should be shareableURLPaginationURL/queryAPI dataQuery/cacheAPI loadingQuery/cacheAPI errorQuery/cacheThemeContext/frameworkLocaleContext/frameworkAuthenticationContext or ReduxPermissionsContext/ReduxShopping cartRedux/global client stateComplex checkoutReduxComplex editorRedux/reducer architectureCross-feature workflowReduxOffline application stateRedux can be a strong choiceDerived valuesSelectors/computationTemporary UI stateLocal</p><p>This isn’t a universal law.</p><p>It’s a starting point.</p><h3>33. What I Would Stop Doing in 2026</h3><p>If I were reviewing a large React application today, these patterns would immediately make me investigate further.</p><blockquote>❌ “Everything belongs in Redux”</blockquote><blockquote>No.</blockquote><blockquote>❌ API response → Redux → local state</blockquote><blockquote>Usually a sign of duplicated ownership.</blockquote><blockquote>❌ Redux for modal state</blockquote><blockquote>Usually unnecessary.</blockquote><blockquote>❌ Redux because the application is large</blockquote><blockquote>Application size alone doesn’t determine state architecture.</blockquote><blockquote>❌ Globalizing state for hypothetical future reuse</blockquote><blockquote>Don’t design for imaginary dependencies.</blockquote><blockquote>❌ Every component importing useSelector</blockquote><blockquote>This can indicate excessive coupling.</blockquote><blockquote>❌ Storing derived values</blockquote><blockquote>Calculate them.</blockquote><blockquote>❌ Using Redux as an API cache by default</blockquote><blockquote>Server state has different requirements.</blockquote><blockquote>❌ Creating abstractions before understanding the problem</blockquote><blockquote>Complexity isn’t automatically architecture.</blockquote><h3>34. The Most Important Metric Isn’t Redux Usage</h3><p>I’ve seen teams measure:</p><pre>Lines of code<br>Number of components<br>Number of Redux slices<br>Number of tests<br>Number of dependencies</pre><p>Those numbers can be useful.</p><p>But the metric I care about more is:</p><blockquote><strong><em>How expensive is it to safely change the application?</em></strong></blockquote><p>Ask:</p><pre>How long does a feature take?<br>How many files does it touch?<br>How frequently does it cause regressions?<br>How difficult is onboarding?<br>How easy is it to trace data flow?<br>How difficult is it to remove old architecture?</pre><p>These tell you much more about the health of the system.</p><h3>35. The Senior Engineer Perspective</h3><p>Early in my career, I cared about choosing the most powerful solution.</p><p>Then I cared about choosing the cleanest architecture.</p><p>With experience, my thinking changed.</p><p>Today, I care more about:</p><pre>Ownership<br>Boundaries<br>Data Flow<br>Coupling<br>Change Cost</pre><p>Because the most sophisticated architecture can still become a maintenance nightmare.</p><p>And the simplest architecture can still become fragile if the boundaries are wrong.</p><p>The goal isn’t:</p><blockquote><strong><em>“Use less Redux.”</em></strong></blockquote><p>The goal is:</p><blockquote><strong><em>“Use the simplest state architecture that keeps ownership and data flow clear.”</em></strong></blockquote><h3>36. Redux Is Still Excellent at One Thing</h3><p>Redux is particularly good at making this explicit:</p><pre>What changed?<br>     ↓<br>Why did it change?<br>     ↓<br>Which action caused it?<br>     ↓<br>Which state changed?<br>     ↓<br>Which components depend on it?</pre><p>For complex applications, that predictability is extremely valuable.</p><p>That’s why I don’t agree with the statement:</p><blockquote><em>“Redux is obsolete.”</em></blockquote><p>It’s not.</p><p>The better statement is:</p><blockquote><strong><em>“Redux is no longer the default answer to every state-management problem.”</em></strong></blockquote><p>That’s a much more accurate description of modern frontend architecture.</p><h3>37. The Real Evolution</h3><p>I’d summarize the evolution like this:</p><pre>EARLY REACT<br><br>React<br>  ↓<br>Complex State<br>  ↓<br>Redux  </pre><p>Then:</p><pre>MODERN REACT<br><br>React<br>  │<br>  ├── Local State<br>  │<br>  ├── Context<br>  │<br>  ├── URL State<br>  │<br>  ├── Server State<br>  │<br>  └── Redux</pre><p>And now the architectural question is:</p><pre>                    STATE<br>                      │<br>              Who owns it?<br>                      │<br>        ┌─────────────┼─────────────┐<br>        │             │             │<br>      UI            Server        Global<br>        │             │             │<br>     Local        Query Cache      Redux</pre><p>That’s the real shift.</p><h3>38. My Rule After 10+ Years</h3><p>If I had to reduce all of this to one rule, it would be:</p><blockquote><strong><em>Start with the smallest possible state boundary. Expand it only when the application’s real relationships prove that you need to.</em></strong></blockquote><p>Start with:</p><pre>Local</pre><p>Then:</p><pre>Lift</pre><p>Then:</p><pre>Context / URL / Query</pre><p>And only when the problem genuinely requires it:</p><pre>Redux</pre><p>This avoids both extremes:</p><pre>Everything is local</pre><p>and:</p><pre>Everything is global</pre><h3>39. The Question I Ask in Code Reviews</h3><p>When I see a new Redux slice, I don’t immediately ask:</p><blockquote><em>“Why are you using Redux?”</em></blockquote><p>I ask:</p><p><em>1. Who owns this state?</em></p><p><em>2. Who consumes it?</em></p><p><em>3. How long does it live?</em></p><p><em>4. Is it server-owned?</em></p><p><em>5. Is it derived?</em></p><p><em>6. Does it cross feature boundaries?</em></p><p><em>7. What happens if we keep it local?</em></p><p><em>8. What complexity does globalizing it introduce?</em></p><p><em>9. Can we remove this state later?</em></p><p><em>10. Will the next developer understand why this state is global?</em></p><p>Those questions usually lead to a much better architectural discussion.</p><h3>40. Final Answer: Do We Still Need Redux?</h3><h3>Yes.</h3><p>But we need to be much more intentional about it.</p><p>Redux is still a strong choice for:</p><pre>Complex client state<br>Cross-feature workflows<br>Complex business processes<br>Rich dashboards<br>Complex editors<br>Offline state<br>Predictable state transitions</pre><p>It is usually unnecessary for:</p><pre>Simple UI state<br>Temporary state<br>Derived values<br>Most server-state caching<br>Component-specific interactions</pre><p>The mistake isn’t using Redux.</p><p>The mistake is using <strong>global state as a shortcut for architectural decisions</strong>.</p><h3>The Final Mental Model</h3><p>Remember this:</p><pre>               WHAT KIND OF STATE?<br>                         │<br>          ┌──────────────┼──────────────┐<br>          │              │              │<br>          ▼              ▼              ▼<br>        LOCAL           URL          SERVER<br>          │              │              │<br>      useState        Router        Query Cache<br>          │              │              │<br>          └──────────────┼──────────────┘<br>                         │<br>                         ▼<br>                  GLOBAL CLIENT<br>                         │<br>                         ▼<br>                       Redux</pre><p>And remember an even simpler rule:</p><blockquote><strong><em>Don’t ask “Can Redux manage this?”</em></strong></blockquote><p>Because Redux can manage almost everything.</p><p>Ask:</p><blockquote><strong><em>“Does this state deserve to be global?”</em></strong></blockquote><p>That is the question that separates simply knowing Redux from designing a frontend architecture.</p><h3>One Last Lesson From 10+ Years</h3><p>The biggest lesson I’ve learned isn’t about Redux.</p><p>It’s about complexity.</p><p>Every:</p><pre>Global State<br>Shared Component<br>Abstraction<br>Dependency<br>Effect<br>Synchronization<br>Architecture Layer</pre><p>creates a relationship that someone will eventually have to understand.</p><p>Some relationships are necessary.</p><p>Some aren’t.</p><p>Good frontend architecture isn’t about eliminating complexity.</p><p>It’s about making sure the complexity that exists is <strong>intentional</strong>.</p><p>So, in 2026:</p><blockquote><strong><em>Redux isn’t dead.</em></strong></blockquote><blockquote><strong><em>Redux isn’t mandatory.</em></strong></blockquote><blockquote><strong><em>Redux isn’t the enemy.</em></strong></blockquote><p>The real enemy is:</p><blockquote><strong><em>Unclear state ownership.</em></strong></blockquote><p>And the best React architecture isn’t the one that uses the most powerful tools.</p><p>It’s the one where a developer can open the codebase and answer one simple question without asking anyone:</p><blockquote><strong><em>“Why does this state live here?”</em></strong></blockquote><p>If your architecture can answer that consistently, you’re probably on the right track.</p><h3>🎯 Senior / Lead-Level Follow-Up Questions</h3><p>If you’re interviewing for a Senior or Lead Frontend role, don’t stop at:</p><blockquote><em>“What is Redux?”</em></blockquote><p>Be prepared for questions like these.</p><p>1. When would you choose Redux over Context?</p><p>2. When should server state not be stored in Redux?</p><p>3. How would you identify unnecessary global state?</p><p>4. How would you refactor a Redux store containing hundreds of slices?</p><p>5. How would you migrate a legacy Redux application incrementally?</p><p>6. How would you prevent every component from becoming coupled to Redux?</p><p>7. How would you model a complex checkout workflow?</p><p>8. How would you handle optimistic updates?</p><p>9. What belongs in RTK Query versus a normal Redux slice?</p><p>10. How do you avoid duplicated state?</p><p>11. How do you identify derived state?</p><p>12. How would you structure Redux in a large Next.js application?</p><p>13. What state should live in the URL?</p><p>14. When would you use useReducer instead of Redux?</p><p>15. How would you debug a Redux application where an action unexpectedly causes many components to rerender?</p><p>16. What are the architectural consequences of making every component Redux-aware?</p><p>17. How would you design Redux boundaries for a multi-team frontend?</p><p>18. When would Redux actually make an application worse?</p><p>19. How would you measure whether removing Redux reduced technical debt?</p><p>20. If you joined a 5-year-old React application using Redux everywhere, what would you inspect first?</p><h3>The takeaway</h3><pre>GOOD FRONTEND ARCHITECTURE<br>                         │<br>                         ▼<br>                 Clear Ownership<br>                         │<br>                         ▼<br>                 Clear Boundaries<br>                         │<br>                         ▼<br>                  Predictable Flow<br>                         │<br>                         ▼<br>                  Low Coupling<br>                         │<br>                         ▼<br>                  Easier Changes</pre><p><strong>Redux is simply one tool inside that architecture.</strong></p><p>The architecture comes first.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad52364bce6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend Technical Debt: The Problems Nobody Notices Until the React App Becomes Huge]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/frontend-technical-debt-the-problems-nobody-notices-until-the-react-app-becomes-huge-1a10f18e0338?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a10f18e0338</guid>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-performance]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 19:06:38 GMT</pubDate>
            <atom:updated>2026-08-25T19:06:38.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9s6Fnm20BdlkNBM" /></figure><blockquote>Lessons from 10+ years of building and maintaining React, TypeScript, Redux, Next.js, and component-driven frontend systems</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7Tyb-PSsNqep3T9t" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*qnWKnNByPrPIhsMu" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*5db4_0zc-NnecedB" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aO2fqcu8nO4lLNtY" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BXiwuHSqaYOONBtH" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*gzftX2tyCJZN392u" /></figure><p>A React application rarely becomes difficult to maintain overnight.</p><p>It happens slowly.</p><p>One useEffect here.</p><p>One global Redux state there.</p><p>One 500-line component that was supposed to be temporary.</p><p>One shared component with 37 props.</p><p>One utils folder that becomes the home for everything nobody knows where to put.</p><p>One API response type copied into three different files.</p><p>One styling decision made five years ago that nobody wants to touch.</p><p>Each decision seems reasonable when it is made.</p><p>The problem is what happens when hundreds or thousands of those decisions accumulate.</p><p>That is <strong>frontend technical debt</strong>.</p><p>And after working with frontend systems for more than a decade, one of the biggest lessons is this:</p><blockquote><strong>The biggest frontend problems are usually not caused by one bad piece of code. They are caused by small decisions that compound over time.</strong></blockquote><h3>The React application that looked perfectly fine</h3><p>Most frontend applications start beautifully.</p><p>You might have:</p><pre>src/<br>  components/<br>  pages/<br>  hooks/<br>  services/<br>  store/</pre><p>Everything is understandable.</p><p>A developer can open the repository and quickly understand where things belong.</p><p>Then the product grows.</p><p>The team grows.</p><p>The number of features grows.</p><p>And suddenly you have:</p><pre>src/<br>  components/<br>    Button/<br>    Modal/<br>    Table/<br>    UserTable/<br>    UserTableNew/<br>    CommonTable/<br>    GenericTable/<br>    SharedTable/<br>    ...<br>  hooks/<br>    useUser.ts<br>    useUsers.ts<br>    useUserData.ts<br>    useFetchUser.ts<br>    useUserDetails.ts<br>    ...<br>  utils/<br>    helpers.ts<br>    common.ts<br>    misc.ts<br>    formatter.ts<br>    newHelpers.ts<br>    oldHelpers.ts<br>  store/<br>    user/<br>    users/<br>    userData/<br>    userProfile/<br>    ...</pre><p>Nobody intentionally designed this mess.</p><p>It evolved.</p><p>And that’s what makes technical debt dangerous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*RVRpnEnakMsCjWE6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*Wz_vv0pZZGTbqCBo" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aQQTYrnAoLCUTNml" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TqVN77jVPbHx2jNl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*JzBg9i8DnUh7Wx8x" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*Vh8HDr6egnRNyEyB" /></figure><h3>1. The first form of technical debt: “We’ll clean it up later”</h3><p>This is probably the most common one.</p><p>You have a feature that needs to ship today.</p><p>The clean implementation might take two days.</p><p>The quick implementation takes three hours.</p><p>So you choose the three-hour implementation.</p><p>That’s not necessarily bad engineering.</p><p>In fact, sometimes it’s exactly the right business decision.</p><p>Technical debt becomes dangerous when the shortcut becomes permanent.</p><p>The problem is that “temporary” code has a habit of becoming production infrastructure.</p><h3>The conversation usually sounds like this:</h3><blockquote>“Let’s just put this in the existing component.”</blockquote><blockquote>“We’ll refactor this after the release.”</blockquote><blockquote>“For now, let’s keep it in Redux.”</blockquote><blockquote>“We’ll make it generic later.”</blockquote><blockquote>“This is the only place we need it.”</blockquote><p>Six months later:</p><p>Nobody remembers why it was implemented that way.</p><p>The original developer may have moved teams.</p><p>The business requirement has changed.</p><p>Three other features now depend on the same behavior.</p><p>And suddenly that three-hour shortcut costs three weeks to undo.</p><h3>2. The 500-line React component</h3><p>One of the clearest signs of frontend debt is the <strong>fat component</strong>.</p><p>It starts innocently:</p><pre>function Checkout() {<br>  // fetch products<br>  // validate coupon<br>  // calculate totals<br>  // manage address<br>  // handle payment<br>  // track analytics<br>  // show modals<br>  // handle errors<br>  // render UI<br>}</pre><p>Then someone adds another requirement.</p><p>Then another.</p><p>Eventually the component becomes responsible for:</p><ul><li>API calls</li><li>business rules</li><li>validation</li><li>state management</li><li>analytics</li><li>permissions</li><li>navigation</li><li>error handling</li><li>styling</li><li>rendering</li></ul><p>At this point, React isn’t really the problem.</p><p>The problem is that <strong>too many responsibilities have crossed the component boundary</strong>.</p><p>A component should not become the place where every concern related to a feature lives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3gyL-yAk2O_86Hl9" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xW4W5-3kKRpvhImX" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lThs_eSBaQ05-q9w" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LQpAzU6eIarH4Bhh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NLFds55MYQEZuLdw" /></figure><h3>3. “Reusable” components can create more debt than they remove</h3><p>This is one of the lessons that becomes more obvious with experience.</p><p>Early in your career, reusable code often feels automatically better.</p><p>Later, you learn that <strong>abstraction has a cost</strong>.</p><p>Consider:</p><pre>&lt;DataTable<br>  data={data}<br>  columns={columns}<br>  loading={loading}<br>  selectable<br>  searchable<br>  sortable<br>  pagination<br>  serverPagination<br>  expandable<br>  virtualized<br>  stickyHeader<br>  renderEmptyState={...}<br>  renderLoadingState={...}<br>  onRowClick={...}<br>/&gt;</pre><p>Technically, it’s reusable.</p><p>But is it maintainable?</p><p>Maybe.</p><p>Maybe not.</p><p>The real question isn’t:</p><blockquote>“Can I reuse this?”</blockquote><p>The better question is:</p><blockquote><strong>“Does this abstraction make the next feature easier to build?”</strong></blockquote><p>A component with 30 props isn’t necessarily reusable architecture.</p><p>Sometimes it’s just several components trapped inside one API.</p><h3>4. The utils folder is where architecture goes to disappear</h3><p>Every large frontend application eventually has a utils folder.</p><p>And initially, that’s fine.</p><p>Then it becomes:</p><pre>utils/<br>  formatDate.ts<br>  formatCurrency.ts<br>  userHelpers.ts<br>  permissions.ts<br>  productHelpers.ts<br>  validation.ts<br>  apiHelpers.ts<br>  stringUtils.ts<br>  common.ts<br>  helpers.ts</pre><p>Eventually nobody knows where new functionality belongs.</p><p>So another helper gets added to common.ts.</p><p>This creates an important architectural problem:</p><p><strong>The code is technically organized, but the domain isn’t.</strong></p><p>Instead of asking:</p><blockquote>“Which utility folder should this go into?”</blockquote><p>Start asking:</p><blockquote>“Which business capability owns this logic?”</blockquote><p>For example:</p><pre>features/<br>  checkout/<br>    components/<br>    hooks/<br>    services/<br>    types/<br>    utils/<br><br>products/<br>    components/<br>    hooks/<br>    services/<br>    types/<br>payments/<br>    components/<br>    hooks/<br>    services/<br>    types/</pre><p>This doesn’t mean every application must use feature-based architecture.</p><p>The principle is more important than the folder names:</p><blockquote><strong>Code should be organized around ownership and responsibility, not just file type.</strong></blockquote><h3>5. Redux becomes the dumping ground</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ukGYmOl9oKamMmfA" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kp6JsWhizQ5e7Scr" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*18s5pE7LL9IJjNzq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EladRSTZ3PUnpy0N" /></figure><p>Redux can be incredibly useful.</p><p>But one of the easiest ways to create frontend debt is to put everything into global state.</p><p>You start with:</p><pre>auth<br>user<br>permissions<br>cart<br>products<br>checkout<br>notifications</pre><p>Then:</p><pre>modal<br>filters<br>selectedTab<br>searchText<br>formState<br>temporaryUIState</pre><p>Eventually Redux becomes a giant application-wide database for anything that might need to be accessed by more than one component.</p><p>The question shouldn’t be:</p><blockquote>“Can this go into Redux?”</blockquote><p>Almost anything can.</p><p>The better question is:</p><blockquote><strong>“Does this state actually need to be global?”</strong></blockquote><h3>Local UI state</h3><p>Things like:</p><pre>isModalOpen<br>activeTab<br>inputValue<br>hoveredItem<br>expandedRow</pre><p>Usually belong close to the UI.</p><h3>Server state</h3><p>Things like:</p><pre>products<br>orders<br>users<br>invoices</pre><p>Need a deliberate data-fetching and caching strategy.</p><h3>Global application state</h3><p>Things like:</p><pre>authentication<br>permissions<br>application-wide preferences<br>cross-feature workflows</pre><p>May genuinely belong in a global store.</p><p>The lesson isn’t “don’t use Redux.”</p><p>It’s:</p><blockquote><strong>Don’t use global state simply because it is available.</strong></blockquote><h3>6. TypeScript can also accumulate technical debt</h3><p>TypeScript is one of the best tools available for large frontend applications.</p><p>But TypeScript doesn’t automatically create a well-designed codebase.</p><p>You can have:</p><pre>const data: any = response.data;</pre><p>throughout the application and still call the project “TypeScript.”</p><p>Or:</p><pre>type User = {<br>  id: string;<br>  name: string;<br>}</pre><p>defined independently in five different places.</p><p>Now you have:</p><pre>User<br>UserType<br>UserModel<br>UserResponse<br>UserDTO<br>UserData</pre><p>And developers spend more time figuring out which type to use than actually using the type system.</p><p>The goal shouldn’t be:</p><blockquote>“Everything must have a type.”</blockquote><p>The goal should be:</p><blockquote><strong>“The important contracts in the system should be explicit.”</strong></blockquote><p>Good TypeScript should make incorrect states difficult to represent.</p><p>Bad TypeScript simply creates more files.</p><h3>7. useEffect becomes the emergency exit</h3><p>Another common source of debt:</p><pre>useEffect(() =&gt; {<br>  // do something<br>}, [something]);</pre><p>Then another:</p><pre>useEffect(() =&gt; {<br>  // synchronize something<br>}, [a, b]);</pre><p>Then:</p><pre>useEffect(() =&gt; {<br>  // fix previous effect<br>}, [data]);</pre><p>Eventually the component becomes a chain of effects reacting to other effects.</p><p>This is where experienced React development becomes less about knowing more APIs and more about <strong>understanding data flow</strong>.</p><p>For example, instead of:</p><pre>const [fullName, setFullName] = useState(&#39;&#39;);<br><br>useEffect(() =&gt; {<br>  setFullName(`${firstName} ${lastName}`);<br>}, [firstName, lastName]);</pre><p>prefer:</p><pre>const fullName = `${firstName} ${lastName}`;</pre><p>This seems like a tiny difference.</p><p>At application scale, thousands of tiny decisions like this matter.</p><h3>8. Next.js introduces a different kind of architectural debt</h3><p>With modern Next.js applications, the question isn’t simply:</p><blockquote>“Which component should render this?”</blockquote><p>You also need to think about:</p><blockquote><strong>“Where should this code execute?”</strong></blockquote><p>Server?</p><p>Client?</p><p>Both?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*mk-WCWxERf2ZgD0w" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*urOkeln6BzWrnt4Z" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ufGqM_sSZQXewTeC" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GN5RUi2p-AQFkVQx" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*deBVGPZpyhZx0dNr" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SpbQLXk5rYXkOghK" /></figure><p>The server/client boundary therefore becomes an important architectural decision.</p><p>A common mistake is turning large parts of the application into Client Components simply because one small piece needs interactivity.</p><p>For example:</p><pre>&quot;use client&quot;;</pre><pre>export default function ProductPage() {<br>  // entire page becomes client-side<br>}</pre><p>because one button needs:</p><pre>const [isOpen, setIsOpen] = useState(false);</pre><p>That may be convenient.</p><p>But convenience at one boundary can create cost elsewhere.</p><p>With Next.js, I increasingly think about architecture in terms of <strong>boundaries</strong>:</p><pre>Server<br>   ↓<br>Data fetching<br>   ↓<br>Feature boundary<br>   ↓<br>Interactive client component<br>   ↓<br>Small local state</pre><p>Rather than:</p><pre>Everything → Client Component</pre><h3>9. Styling debt is real</h3><p>Frontend teams often think technical debt means JavaScript and TypeScript only.</p><p>It doesn’t.</p><p>Styling creates debt too.</p><p>Especially in long-lived applications using CSS-in-JS, styled-components, CSS modules, utility classes, legacy CSS, and multiple design systems at the same time.</p><p>You eventually see:</p><pre>Button<br>ButtonV2<br>PrimaryButton<br>NewButton<br>StyledButton<br>CommonButton<br>LegacyButton</pre><p>And nobody knows which one should be used.</p><p>The bigger problem isn’t the styling technology.</p><p>It’s the absence of <strong>design-system ownership and component boundaries</strong>.</p><p>A mature frontend should answer:</p><ul><li>Which components are public/shared?</li><li>Which are feature-specific?</li><li>Who owns them?</li><li>How are variants created?</li><li>How are breaking changes handled?</li><li>What belongs in the design system?</li><li>What should never become shared?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/0*wlLX50Id9FpW1ErA" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-S-_ZYlsjHRE4LSg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YpLm9McokIi7kn4X" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Gajch-4TZXn-Zen2" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jia8nhGVSzmm-zJM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*H0Ge3db9RqnIwmgW" /></figure><h3>10. Copy-paste is sometimes better than abstraction</h3><p>This is probably one of the hardest lessons for experienced developers to accept.</p><p>If you have:</p><pre>ComponentA<br>ComponentB</pre><p>and they currently look 90% similar, you don’t necessarily need:</p><pre>&lt;UniversalComponent /&gt;</pre><p>Sometimes duplication is cheaper.</p><p>Why?</p><p>Because you don’t know yet whether the two implementations will continue evolving together.</p><p>A little duplication can be healthy.</p><p>Premature abstraction can create a dependency that lasts for years.</p><p>My rule is:</p><blockquote><strong>Duplicate twice. Understand the pattern. Abstract when the third use case proves the abstraction.</strong></blockquote><p>Not a universal rule — but a useful default.</p><h3>11. Dependency debt is another silent killer</h3><p>Large frontend applications accumulate dependencies quickly.</p><p>A five-year-old application might contain libraries for:</p><ul><li>state management</li><li>forms</li><li>validation</li><li>date handling</li><li>UI</li><li>animations</li><li>charts</li><li>data fetching</li><li>styling</li><li>testing</li><li>utility functions</li></ul><p>Some libraries are barely used anymore.</p><p>Others have been replaced by platform capabilities or framework features.</p><p>But removing dependencies feels risky.</p><p>So they stay.</p><p>Eventually:</p><pre>package.json</pre><p>becomes an architectural document nobody wants to read.</p><p>Dependency management isn’t just about security updates.</p><p>It’s about asking:</p><blockquote><strong>“Does this dependency still justify its existence?”</strong></blockquote><h3>12. The real cost of technical debt isn’t ugly code</h3><p>This is the most important point.</p><p>Technical debt doesn’t matter because developers dislike messy code.</p><p>It matters because it changes the economics of development.</p><p>A healthy application might behave like:</p><pre>Feature request<br>      ↓<br>Small change<br>      ↓<br>Tests<br>      ↓<br>Deploy</pre><p>A heavily indebted application becomes:</p><pre>Feature request<br>      ↓<br>Find where this behavior lives<br>      ↓<br>Understand 5-year-old code<br>      ↓<br>Check Redux dependencies<br>      ↓<br>Check shared component<br>      ↓<br>Check side effects<br>      ↓<br>Check styling overrides<br>      ↓<br>Change code<br>      ↓<br>Something else breaks<br>      ↓<br>Fix regression<br>      ↓<br>Add another workaround</pre><p>The codebase starts charging <strong>interest</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*Gr8jWzgc63tZpAdc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wr4uFvp88_axXXLb" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cfdlH8_HXnkflDnc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AGuorvXrWoQ4lTa1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kj3nEBTc5o4Igrd_" /></figure><p>That’s technical debt.</p><h3>13. The most dangerous metric: “It still works”</h3><p>A frontend application can work perfectly and still have enormous technical debt.</p><p>The application loads.</p><p>Users can log in.</p><p>Orders can be placed.</p><p>The dashboard works.</p><p>CI is green.</p><p>So everyone assumes the codebase is healthy.</p><p>Then a new feature arrives.</p><p>And suddenly a seemingly simple change takes two weeks.</p><p>That’s when the debt becomes visible.</p><p>A better question than:</p><blockquote>“Does the application work?”</blockquote><p>is:</p><blockquote><strong>“How expensive is it to safely change the application?”</strong></blockquote><p>That’s the metric I care about more as systems grow.</p><h3>14. How do you actually reduce frontend technical debt?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B2aG6EBfkQ9NmAQ3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RIzgiVsR_K9nXOAi" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FQtydmyhbd1HkLoG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wdrDyv4bwOJoJaVP" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pYcZbHrtsHyU031U" /></figure><p>Not by rewriting everything.</p><p>This is another mistake I’ve seen repeatedly.</p><p>A team realizes the architecture is bad and proposes:</p><blockquote>“Let’s rebuild it from scratch.”</blockquote><p>Six months later:</p><ul><li>the old application still exists</li><li>the new application is incomplete</li><li>both systems require maintenance</li><li>the team is exhausted</li><li>business features are delayed</li></ul><p>A better approach is <strong>incremental architecture improvement</strong>.</p><h3>Step 1: Find the expensive areas</h3><p>Don’t refactor everything.</p><p>Find the areas where developers repeatedly struggle.</p><p>For example:</p><pre>Checkout<br>User Management<br>Search<br>Dashboard<br>Reporting</pre><p>Ask:</p><ul><li>Where do bugs happen repeatedly?</li><li>Which files are scary to modify?</li><li>Which components are constantly changed?</li><li>Which areas take longest to onboard?</li><li>Which features require touching unrelated modules?</li></ul><p>Those are your debt hotspots.</p><h3>Step 2: Measure change cost</h3><p>You don’t need complicated tooling.</p><p>Track things such as:</p><pre>Average time to implement feature<br>Average PR size<br>Number of files touched<br>Regression frequency<br>Build time<br>Test execution time<br>Deployment frequency</pre><p>Technical debt becomes easier to prioritize when you connect it to engineering outcomes.</p><h3>15. Introduce boundaries before introducing patterns</h3><p>This is one of my strongest recommendations.</p><p>Don’t start with:</p><blockquote>“Should we use Clean Architecture?”</blockquote><p>or:</p><blockquote>“Should we use Feature-Sliced Design?”</blockquote><p>Start with:</p><blockquote><strong>“What is allowed to depend on what?”</strong></blockquote><p>For example:</p><pre>app<br> ↓<br>features<br> ↓<br>shared</pre><p>And:</p><pre>features/product<br>      ↓<br>shared/ui<br>shared/lib</pre><p>But:</p><pre>shared/ui<br>      X<br>features/product</pre><p>The exact architecture can change.</p><p>The dependency direction is what matters.</p><h3>16. A practical structure for a large React/Next.js application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D-0aKYcxv67mbAuV" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*_cDhSOBZIcBpOK6P" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*RSX21MZ05G0NYC16" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*p21C2nkIvpTO5MM5" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q0yuiM7DEnHC6yoP" /></figure><p>There isn’t one perfect structure.</p><p>But a feature-oriented structure can provide useful boundaries:</p><pre>src/<br>  app/<br>    routes/<br>    providers/<br>    layouts/<br><br><br>features/<br>    checkout/<br>      components/<br>      hooks/<br>      services/<br>      state/<br>      types/<br>    products/<br>      components/<br>      hooks/<br>      services/<br>      state/<br>      types/<br>    users/<br>      components/<br>      hooks/<br>      services/<br>      state/<br>      types/<br>  shared/<br>    ui/<br>    hooks/<br>    lib/<br>    types/</pre><p>The important part isn’t copying this folder structure.</p><p>The important part is making ownership explicit.</p><h3>17. What I would stop doing on a large frontend</h3><p>If I were joining a large React codebase today, I’d be very careful about:</p><blockquote><em>❌ </em><strong><em>Globalizing every piece of state</em></strong></blockquote><p>Not everything needs Redux.</p><blockquote><em>❌ </em><strong><em>Creating generic components too early</em></strong></blockquote><p>Abstraction should follow understanding.</p><blockquote><em>❌ </em><strong><em>Adding </em></strong><strong><em>useEffect automatically</em></strong></blockquote><p>Effects are not a replacement for thinking about data flow.</p><blockquote><em>❌ </em><strong><em>Creating another </em></strong><strong><em>utils.ts</em></strong></blockquote><p>Ask which domain owns the logic.</p><blockquote><em>❌ </em><strong><em>Making everything a Client Component</em></strong></blockquote><p>Especially in a Next.js App Router application.</p><blockquote><em>❌ </em><strong><em>Adding libraries for problems the platform already solves</em></strong></blockquote><p>Every dependency becomes part of your long-term maintenance surface.</p><blockquote><em>❌ </em><strong><em>Refactoring without measuring the problem</em></strong></blockquote><p>“Clean code” isn’t a business metric.</p><p>Reduced change cost is.</p><h3>18. What I would do differently after 10+ years</h3><p>The biggest shift isn’t technical.</p><p>It’s philosophical.</p><p>Earlier in a career, the instinct can be:</p><blockquote>“How can I write this better?”</blockquote><p>With more experience, the question becomes:</p><blockquote><strong>“How can I make this system easier for the next developer to change?”</strong></blockquote><p>That’s a completely different goal.</p><p>It changes how you think about:</p><ul><li>components</li><li>abstractions</li><li>Redux</li><li>TypeScript</li><li>Next.js</li><li>styling</li><li>testing</li><li>architecture</li><li>dependencies</li></ul><p>You stop optimizing individual files.</p><p>You start optimizing <strong>the system’s ability to evolve</strong>.</p><h3>19. Technical debt is not the enemy</h3><p>This is important.</p><p>You cannot eliminate technical debt.</p><p>And you shouldn’t try.</p><p>Every product makes trade-offs.</p><p>Shipping quickly creates debt.</p><p>Supporting multiple business requirements creates debt.</p><p>Legacy browser support creates debt.</p><p>Changing product direction creates debt.</p><p>Acquiring another application creates debt.</p><p>Even good architectural decisions can become debt when the surrounding system changes.</p><p>The goal isn’t:</p><blockquote>“Zero technical debt.”</blockquote><p>The goal is:</p><blockquote><strong>“Debt that we understand, control, and can pay down when it starts affecting delivery.”</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rMuII5zl-KoO8eGp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*vGcDskBRPBzXeM_r" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vJhZtqse3l4Ryza4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YooBfudQXF_NuCDo" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LKfpl49ENW7VThfK" /></figure><h3>20. The final lesson</h3><p>A large React application doesn’t become difficult because it has too many components.</p><p>It becomes difficult when <strong>the relationships between those components become impossible to reason about</strong>.</p><p>It doesn’t become difficult because Redux exists.</p><p>It becomes difficult when nobody knows <strong>what belongs in Redux</strong>.</p><p>It doesn’t become difficult because TypeScript has many types.</p><p>It becomes difficult when <strong>types stop representing meaningful boundaries</strong>.</p><p>It doesn’t become difficult because Next.js has Server and Client Components.</p><p>It becomes difficult when <strong>the team doesn’t understand where the server/client boundary belongs</strong>.</p><p>And it doesn’t become difficult because the code is old.</p><p>It becomes difficult when <strong>old decisions can no longer be changed safely</strong>.</p><p>That’s the real definition of frontend technical debt.</p><blockquote><strong>Technical debt is not code that looks ugly.</strong></blockquote><blockquote><strong>Technical debt is code that makes change unnecessarily expensive.</strong></blockquote><p>And that’s why the best frontend architecture isn’t the one that looks perfect on day one.</p><p>It’s the one that still lets your team move quickly five years later.</p><h3>A practical checklist for your next React codebase</h3><p>Before adding a new feature, ask:</p><ul><li>Does this state really need to be global?</li><li>Is this data server state or UI state?</li><li>Does this component have more than one responsibility?</li><li>Are we creating an abstraction because we need it or because it feels cleaner?</li><li>Which feature owns this business logic?</li><li>Can this code remain server-side in Next.js?</li><li>Does this need an Effect?</li><li>Are we introducing another dependency?</li><li>Is this component genuinely shared?</li><li>Will the next developer understand this code without asking me?</li></ul><p>These questions are often more valuable than another list of React “best practices.”</p><h3>Follow-up questions worth discussing</h3><h3>1. “When Should You Actually Use Redux in a React Application?”</h3><p>Go deeper into:</p><ul><li>local state</li><li>Context</li><li>Redux Toolkit</li><li>RTK Query</li><li>server state</li><li>URL state</li><li>form state</li></ul><h3>2. “How Do You Refactor a 1,000-Line React Component Without Breaking Production?”</h3><p>A practical step-by-step refactoring case study.</p><h3>3. “Are Reusable React Components Actually Making Your Application Worse?”</h3><p>Discuss abstraction, prop explosion, composition, and design systems.</p><h3>4. “Next.js Server vs Client Components: The Architecture Decisions That Matter”</h3><p>Focus on boundaries rather than simply explaining &quot;use client&quot;.</p><h3>5. “TypeScript at Scale: When Strong Typing Becomes Type Complexity”</h3><p>Cover:</p><ul><li>any</li><li>generics</li><li>DTOs</li><li>domain types</li><li>API types</li><li>type duplication</li><li>type inference</li></ul><h3>6. “The utils Folder Is a Design Smell: What Should Replace It?”</h3><p>A highly relatable topic for experienced frontend developers.</p><h3>7. “How to Know When Your React Application Needs an Architecture Refactor”</h3><p>Create a practical scoring system around:</p><pre>Change cost<br>Bug frequency<br>Dependency coupling<br>Component size<br>State complexity<br>Build time<br>Testability<br>Developer onboarding</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a10f18e0338" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Design Patterns to Type-Level Architecture — A Practical Guide from 10+ Years of Production…]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/from-design-patterns-to-type-level-architecture-a-practical-guide-from-10-years-of-production-1f89f025cba8?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f89f025cba8</guid>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 16:32:55 GMT</pubDate>
            <atom:updated>2026-08-24T16:32:55.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Design Patterns to Type-Level Architecture — A Practical Guide from 10+ Years of Production Experience</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfoRifeOb7yoJhK4I7rMzQ.png" /></figure><blockquote>TypeScript Design Patterns Every Developer Should Know</blockquote><blockquote>From Singleton and Factory to Discriminated Unions, Generics, Repository, Strategy and Advanced Type-Level Patterns</blockquote><p>TypeScript is often introduced as:</p><blockquote><em>“JavaScript with types.”</em></blockquote><p>After working with TypeScript for more than a decade across frontend applications, React architectures, APIs, shared libraries, dashboards, design systems, and large-scale applications, I would describe it differently:</p><blockquote><strong><em>TypeScript is a tool for expressing architectural intent in code.</em></strong></blockquote><p>The biggest advantage isn’t that TypeScript can tell you that name is a string.</p><p>The real advantage is that TypeScript can help you answer questions such as:</p><ul><li>Can this state actually exist?</li><li>Can this API return an invalid response?</li><li>Can a ProductId accidentally be passed where a UserId is expected?</li><li>Can a component receive an impossible combination of props?</li><li>Can we add a new state without forgetting to update every consumer?</li><li>Can we change an implementation without changing every caller?</li><li>Can we make a reusable abstraction without losing type safety?</li></ul><p>That’s where <strong>patterns</strong> become valuable.</p><p>But there is an important distinction:</p><blockquote><strong><em>A design pattern is not something you add to code. It’s something you recognize when a recurring problem appears.</em></strong></blockquote><p>This article covers the patterns I consider most valuable for modern TypeScript development, especially for developers working on large frontend and full-stack applications.</p><h3>1. The TypeScript Pattern Landscape</h3><p>Before looking at individual patterns, let’s divide them into four groups.</p><pre>                     TYPESCRIPT PATTERNS<br>                                │<br>        ┌───────────────────────┼────────────────────────┐<br>        │                       │                        │<br>        ▼                       ▼                        ▼<br>   CREATIONAL              STRUCTURAL                BEHAVIORAL<br>        │                       │                        │<br>        ├─ Factory              ├─ Adapter              ├─ Strategy<br>        ├─ Builder              ├─ Facade               ├─ Observer<br>        ├─ Singleton            ├─ Decorator            ├─ Command<br>        └─ Abstract Factory     ├─ Repository           └─ State<br>                                └─ Composition<br>                                <br>                                +<br>                                <br>                    TYPESCRIPT TYPE PATTERNS<br>                                │<br>        ┌───────────────────────┼────────────────────────┐<br>        │                       │                        │<br>        ▼                       ▼                        ▼<br>    Generics                Unions                  Type Safety<br>        │                       │                        │<br>        ├─ Constraints          ├─ Discriminated         ├─ Type Guards<br>        ├─ keyof                  Unions                ├─ Branded Types<br>        ├─ typeof               ├─ Result Types          ├─ Exhaustiveness<br>        ├─ infer                └─ State Modeling        └─ satisfies<br>        └─ Mapped Types</pre><p>The interesting part is that modern applications rarely use just one pattern.</p><p>A production architecture might look like:</p><pre>React Component<br>      │<br>      ▼<br>Custom Hook<br>      │<br>      ▼<br>Service<br>      │<br>      ▼<br>Repository<br>      │<br>      ▼<br>API Client<br>      │<br>      ▼<br>Result&lt;T, E&gt;<br>      │<br>      ▼<br>Discriminated Union</pre><p>And the entire flow can be strongly typed.</p><p>That’s where TypeScript becomes much more than autocomplete.</p><h3>2. The Most Important Rule: Don’t Start With the Pattern</h3><p>One of the biggest mistakes I see from developers learning design patterns is this:</p><pre>&quot;I know Factory Pattern.<br>Where can I use Factory?&quot;</pre><p>That’s backwards.</p><p>Instead ask:</p><pre>What problem do I have?<br>        ↓<br>Where is the complexity?<br>        ↓<br>What is changing frequently?<br>        ↓<br>What should remain stable?<br>        ↓<br>What abstraction reduces that complexity?<br>        ↓<br>Is a known pattern appropriate?</pre><p>For example:</p><h3>Problem</h3><p>You have:</p><pre>if (paymentMethod === &quot;card&quot;) {<br>  // ...<br>}<br><br>if (paymentMethod === &quot;paypal&quot;) {<br>  // ...<br>}<br>if (paymentMethod === &quot;upi&quot;) {<br>  // ...<br>}</pre><pre>Don’t immediately think:</pre><blockquote><em>“I need Strategy.”</em></blockquote><p>First ask:</p><blockquote><em>“Are these algorithms genuinely interchangeable?”</em></blockquote><p>If yes, Strategy might be appropriate.</p><p>If the problem is actually invalid state combinations, a <strong>discriminated union</strong> might be the better solution.</p><p>That’s the difference between knowing patterns and knowing <strong>when to use patterns</strong>.</p><h3>3. Singleton Pattern</h3><p>Singleton guarantees that only one instance of a class exists.</p><p>A basic implementation:</p><pre>class Logger {<br>  private static instance: Logger;<br><br>private constructor() {}<br>  static getInstance(): Logger {<br>    if (!Logger.instance) {<br>      Logger.instance = new Logger();<br>    }<br>    return Logger.instance;<br>  }<br>  log(message: string) {<br>    console.log(message);<br>  }<br>}</pre><p>Usage:</p><pre>const logger = Logger.getInstance();<br>logger.log(&quot;Application started&quot;);</pre><h3>Architecture</h3><pre>                  Logger<br>                    │<br>             getInstance()<br>                    │<br>                    ▼<br>             ┌───────────┐<br>             │  Logger   │<br>             │ Instance  │<br>             └───────────┘<br>               ▲       ▲<br>               │       │<br>          Service A  Service B</pre><h3>Good use cases</h3><ul><li>Logger</li><li>Analytics manager</li><li>Configuration manager</li><li>Certain connection managers</li><li>Certain infrastructure services</li></ul><h3>But here’s the senior-level concern</h3><p>Singleton introduces global access.</p><p>That can make:</p><ul><li>testing harder</li><li>dependencies invisible</li><li>lifecycle management complicated</li><li>state unpredictable</li></ul><p>So don’t turn everything into a Singleton.</p><p>In modern frontend applications, a module-level instance, dependency injection, React Context, or a dedicated state-management mechanism may be more appropriate.</p><h3>Interview question</h3><p><strong>Why can Singleton become an anti-pattern?</strong></p><p>Because it introduces global shared state and hidden dependencies.</p><h3>4. Factory Pattern</h3><p>Factory moves object creation away from the consumer.</p><p>Without Factory:</p><pre>const payment = new StripePayment();</pre><p>With Factory:</p><pre>const payment = PaymentFactory.create(&quot;stripe&quot;);</pre><p>Example:</p><pre>interface PaymentProvider {<br>  pay(amount: number): Promise&lt;void&gt;;<br>}<br><br>class StripePayment implements PaymentProvider {<br>  async pay(amount: number) {<br>    console.log(&quot;Stripe:&quot;, amount);<br>  }<br>}<br>class PayPalPayment implements PaymentProvider {<br>  async pay(amount: number) {<br>    console.log(&quot;PayPal:&quot;, amount);<br>  }<br>}<br>class PaymentFactory {<br>  static create(<br>    provider: &quot;stripe&quot; | &quot;paypal&quot;<br>  ): PaymentProvider {<br>    switch (provider) {<br>      case &quot;stripe&quot;:<br>        return new StripePayment();<br>      case &quot;paypal&quot;:<br>        return new PayPalPayment();<br>    }<br>  }<br>}</pre><h3>Diagram</h3><pre>              PaymentFactory<br>                       │<br>          ┌────────────┴────────────┐<br>          │                         │<br>       &quot;stripe&quot;                  &quot;paypal&quot;<br>          │                         │<br>          ▼                         ▼<br>     StripePayment             PayPalPayment</pre><h3>When Factory makes sense</h3><p>Use it when:</p><ul><li>creation logic is complicated</li><li>multiple implementations exist</li><li>consumers shouldn’t know concrete classes</li><li>the implementation can change independently</li></ul><h3>When I wouldn’t use it</h3><p>If all you have is:</p><pre>new User();</pre><p>a Factory probably adds unnecessary abstraction.</p><h3>5. Abstract Factory</h3><p>Abstract Factory is useful when you create <strong>families of related objects</strong>.</p><p>Imagine a UI system supporting multiple platforms.</p><pre>interface Button {<br>  render(): void;<br>}<br><br>interface Modal {<br>  open(): void;<br>}<br><br>interface UIFactory {<br>  createButton(): Button;<br>  createModal(): Modal;<br>}</pre><p>Architecture:</p><pre>                  UIFactory<br>                    │<br>           ┌────────┴────────┐<br>           ▼                 ▼<br>     WebUIFactory       MobileUIFactory<br>           │                 │<br>      ┌────┴────┐       ┌────┴────┐<br>      ▼         ▼       ▼         ▼<br>   Button     Modal   Button     Modal</pre><p>This is powerful, but it’s also easy to over-engineer.</p><p>For most frontend applications, simpler composition is often preferable.</p><h3>6. Builder Pattern</h3><p>Builder is useful when object construction has many optional or sequential configuration steps.</p><pre>class RequestBuilder {<br>  private config: RequestInit = {};<br><br>setMethod(method: string) {<br>    this.config.method = method;<br>    return this;<br>  }<br>  setHeaders(headers: HeadersInit) {<br>    this.config.headers = headers;<br>    return this;<br>  }<br>  setBody(body: BodyInit) {<br>    this.config.body = body;<br>    return this;<br>  }<br>  build() {<br>    return this.config;<br>  }<br>}</pre><p>Usage:</p><pre>const request = new RequestBuilder()<br>  .setMethod(&quot;POST&quot;)<br>  .setHeaders({<br>    &quot;Content-Type&quot;: &quot;application/json&quot;<br>  })<br>  .setBody(JSON.stringify(data))<br>  .build();</pre><h3>The important idea</h3><p>Builder isn’t about making code look fluent.</p><p>It’s about making <strong>complex construction explicit and controlled</strong>.</p><h3>7. Adapter Pattern</h3><p>This is one of the most useful patterns in real-world application development.</p><p>Suppose your application expects:</p><pre>interface PaymentGateway {<br>  pay(amount: number): Promise&lt;void&gt;;<br>}</pre><p>But a third-party SDK gives you:</p><pre>class LegacyPaymentSDK {<br>  makePayment(value: number) {<br>    // third-party implementation<br>  }<br>}</pre><p>Create an Adapter:</p><pre>class PaymentAdapter implements PaymentGateway {<br>  constructor(<br>    private readonly sdk: LegacyPaymentSDK<br>  ) {}<br><br>async pay(amount: number) {<br>    this.sdk.makePayment(amount);<br>  }<br>}</pre><h3>Architecture</h3><pre>Application<br>     │<br>     ▼<br>PaymentGateway<br>     ▲<br>     │<br>PaymentAdapter<br>     │<br>     ▼<br>Third-party SDK</pre><h3>Why this is powerful</h3><p>Your application now depends on:</p><pre>PaymentGateway</pre><p>instead of:</p><pre>Stripe<br>PayPal<br>LegacySDK<br>SomeFutureProvider</pre><p>This gives you a stable internal contract.</p><h3>8. Facade Pattern</h3><p>Facade hides complexity behind a simpler API.</p><p>Imagine login requires:</p><pre>Authentication<br>     +<br>User Service<br>     +<br>Permissions<br>     +<br>Notification<br>     +<br>Analytics</pre><p>Instead of exposing all of that to the component:</p><pre>auth.login();<br>user.load();<br>permission.load();<br>analytics.track();</pre><p>create:</p><pre>class AppFacade {<br>  async login(username: string, password: string) {<br>    const token = await auth.login(username, password);<br><br>const user = await userService.getUser(token);<br>    await permissionService.load(user);<br>    analytics.track(&quot;login&quot;);<br>    return user;<br>  }<br>}</pre><p>Now:</p><pre>await appFacade.login(username, password);</pre><h3>Diagram</h3><pre>               Component<br>                     │<br>                     ▼<br>                 AppFacade<br>                     │<br>       ┌─────────────┼─────────────┐<br>       ▼             ▼             ▼<br>     Auth          User        Permission<br>    Service       Service       Service</pre><p>This is especially useful for large application workflows.</p><h3>9. Decorator Pattern</h3><p>Decorator adds behavior without modifying the original implementation.</p><pre>interface Logger {<br>  log(message: string): void;<br>}</pre><p>Base implementation:</p><pre>class ConsoleLogger implements Logger {<br>  log(message: string) {<br>    console.log(message);<br>  }<br>}</pre><p>Decorator:</p><pre>class TimestampLogger implements Logger {<br>  constructor(<br>    private readonly logger: Logger<br>  ) {}<br><br>log(message: string) {<br>    this.logger.log(<br>      `[${new Date().toISOString()}] ${message}`<br>    );<br>  }<br>}</pre><p>Usage:</p><pre>const logger = new TimestampLogger(<br>  new ConsoleLogger()<br>);</pre><h3>Architecture</h3><pre>Logger<br>  │<br>  ▼<br>ConsoleLogger<br>  │<br>  ▼<br>TimestampLogger<br>  │<br>  ▼<br>AdditionalDecorator</pre><p>Decorator-like ideas appear in:</p><ul><li>middleware</li><li>wrappers</li><li>Higher-Order Components</li><li>logging</li><li>caching</li><li>authorization</li><li>instrumentation</li></ul><h3>10. Strategy Pattern</h3><p>Strategy is one of the most useful patterns for eliminating conditional business logic.</p><p>Suppose:</p><pre>type CustomerType =<br>  | &quot;regular&quot;<br>  | &quot;premium&quot;<br>  | &quot;enterprise&quot;;</pre><p>Instead of:</p><pre>function calculateDiscount(<br>  type: CustomerType,<br>  price: number<br>) {<br>  if (type === &quot;regular&quot;) {<br>    return price;<br>  }<br><br>if (type === &quot;premium&quot;) {<br>    return price * 0.9;<br>  }<br>  return price * 0.8;<br>}</pre><p>Use strategies:</p><pre>interface DiscountStrategy {<br>  calculate(price: number): number;<br>}<br><br>class RegularDiscount implements DiscountStrategy {<br>  calculate(price: number) {<br>    return price;<br>  }<br>}<br>class PremiumDiscount implements DiscountStrategy {<br>  calculate(price: number) {<br>    return price * 0.9;<br>  }<br>}<br>class EnterpriseDiscount implements DiscountStrategy {<br>  calculate(price: number) {<br>    return price * 0.8;<br>  }<br>}</pre><h3>Diagram</h3><pre>                  Order<br>                      │<br>                      ▼<br>              DiscountStrategy<br>                      │<br>          ┌───────────┼───────────┐<br>          ▼           ▼           ▼<br>       Regular      Premium    Enterprise<br>       Strategy     Strategy    Strategy</pre><h3>The real benefit</h3><p>Adding another strategy doesn’t necessarily require modifying the existing business logic.</p><p>This is where Strategy connects strongly with the <strong>Open/Closed Principle</strong>.</p><h3>11. Observer Pattern</h3><p>Observer creates a one-to-many relationship.</p><pre>                 Subject<br>                     │<br>          ┌──────────┼──────────┐<br>          ▼          ▼          ▼<br>      Observer A Observer B Observer C</pre><p>TypeScript implementation:</p><pre>type Listener&lt;T&gt; = (value: T) =&gt; void;<br><br>class EventEmitter&lt;T&gt; {<br>  private listeners = new Set&lt;Listener&lt;T&gt;&gt;();<br>  subscribe(listener: Listener&lt;T&gt;) {<br>    this.listeners.add(listener);<br>    return () =&gt; {<br>      this.listeners.delete(listener);<br>    };<br>  }<br>  emit(value: T) {<br>    this.listeners.forEach(listener =&gt; {<br>      listener(value);<br>    });<br>  }<br>}</pre><p>Usage:</p><pre>const emitter = new EventEmitter&lt;string&gt;();<br><br>const unsubscribe = emitter.subscribe(message =&gt; {<br>  console.log(message);<br>});<br>emitter.emit(&quot;Hello&quot;);<br>unsubscribe();</pre><h3>The senior-level detail</h3><p>Notice that subscribe() returns an unsubscribe function.</p><p>That’s not a cosmetic detail.</p><p>It’s lifecycle management.</p><p>Without cleanup, observers can cause:</p><ul><li>memory leaks</li><li>duplicate events</li><li>stale closures</li><li>unexpected side effects</li></ul><h3>12. Command Pattern</h3><p>Command represents an action as an object.</p><pre>interface Command {<br>  execute(): void;<br>}</pre><p>Example:</p><pre>class SaveCommand implements Command {<br>  execute() {<br>    console.log(&quot;Saving...&quot;);<br>  }<br>}<br><br>class UndoCommand implements Command {<br>  execute() {<br>    console.log(&quot;Undo&quot;);<br>  }<br>}</pre><p>This becomes useful when commands need:</p><ul><li>history</li><li>undo/redo</li><li>queues</li><li>retries</li><li>delayed execution</li><li>logging</li></ul><h3>Diagram</h3><pre>User Action<br>    │<br>    ▼<br> Command<br>    │<br>    ├── execute()<br>    │<br>    ▼<br> Receiver</pre><h3>13. Repository Pattern</h3><p>This is one of my favorite architectural patterns for applications with non-trivial data access.</p><pre>UI<br> │<br> ▼<br>Hook / Controller<br> │<br> ▼<br>Service<br> │<br> ▼<br>Repository<br> │<br> ├── REST<br> ├── GraphQL<br> ├── IndexedDB<br> └── Cache</pre><p>Define the contract:</p><pre>interface UserRepository {<br>  getUser(id: string): Promise&lt;User&gt;;<br>  getUsers(): Promise&lt;User[]&gt;;<br>}</pre><p>Implementation:</p><pre>class ApiUserRepository implements UserRepository {<br>  async getUser(id: string) {<br>    const response = await fetch(`/users/${id}`);<br><br>return response.json();<br>  }<br>  async getUsers() {<br>    const response = await fetch(&quot;/users&quot;);<br>    return response.json();<br>  }<br>}</pre><p>Now the business layer depends on:</p><pre>UserRepository</pre><p>not:</p><pre>fetch()<br>axios()<br>graphqlClient()</pre><p>This becomes particularly valuable when the data source changes.</p><h3>14. Composition Pattern</h3><p>For modern frontend development, this is arguably more important than inheritance-based patterns.</p><p>Instead of:</p><pre>MegaComponent<br> ├── Authentication<br> ├── Table<br> ├── Filters<br> ├── Modal<br> ├── Notifications<br> ├── API calls<br> └── Business logic</pre><p>prefer:</p><pre>Dashboard<br> ├── Header<br> ├── Sidebar<br> ├── FilterPanel<br> ├── DataTable<br> └── NotificationPanel</pre><p>React example:</p><pre>&lt;Dashboard&gt;<br>  &lt;Header /&gt;<br>  &lt;Sidebar /&gt;<br>  &lt;MainContent /&gt;<br>&lt;/Dashboard&gt;</pre><h3>Senior-level lesson</h3><blockquote><em>Composition is often the most maintainable form of reuse in frontend architecture.</em></blockquote><h3>15. Discriminated Union Pattern</h3><p>Now we get into patterns where TypeScript itself becomes an architectural tool.</p><p>Consider an API request:</p><pre>type RequestState =<br>  | {<br>      status: &quot;idle&quot;;<br>    }<br>  | {<br>      status: &quot;loading&quot;;<br>    }<br>  | {<br>      status: &quot;success&quot;;<br>      data: User[];<br>    }<br>  | {<br>      status: &quot;error&quot;;<br>      error: string;<br>    };</pre><p>Now:</p><pre>function render(state: RequestState) {<br>  switch (state.status) {<br>    case &quot;idle&quot;:<br>      return &quot;Nothing started&quot;;<br><br>    case &quot;loading&quot;:<br>      return &quot;Loading...&quot;;<br>    case &quot;success&quot;:<br>      return state.data;<br>    case &quot;error&quot;:<br>      return state.error;<br>  }<br>}</pre><p>TypeScript understands:</p><pre>status = &quot;success&quot;<br>        ↓<br>data exists<br><br>status = &quot;error&quot;<br>        ↓<br>error exists</pre><h3>This is much safer than:</h3><pre>interface State {<br>  loading: boolean;<br>  data?: User[];<br>  error?: string;<br>}</pre><p>Because that model allows impossible states:</p><pre>{<br>  loading: true,<br>  data: [...],<br>  error: &quot;Something failed&quot;<br>}</pre><p>The discriminated union makes invalid combinations much harder to represent.</p><h3>One of my strongest TypeScript rules</h3><blockquote><strong><em>Model valid states instead of creating optional properties and hoping developers use them correctly.</em></strong></blockquote><h3>16. Result Type Pattern</h3><p>API and business operations frequently have two outcomes:</p><pre>Success<br>   OR<br>Failure</pre><p>Model that explicitly.</p><pre>type Result&lt;T, E&gt; =<br>  | {<br>      success: true;<br>      data: T;<br>    }<br>  | {<br>      success: false;<br>      error: E;<br>    };</pre><p>Usage:</p><pre>function getUser(): Result&lt;User, string&gt; {<br>  return {<br>    success: true,<br>    data: user<br>  };<br>}</pre><p>Consumer:</p><pre>const result = getUser();<br><br>if (result.success) {<br>  console.log(result.data);<br>} else {<br>  console.error(result.error);<br>}</pre><h3>Architecture</h3><pre>             Service<br>                │<br>                ▼<br>          Result&lt;T, E&gt;<br>           /       \<br>          /         \<br>         ▼           ▼<br>      Success      Failure<br>        │             │<br>       data          error</pre><p>This is particularly useful when you want business failures to be explicit rather than relying entirely on exceptions.</p><h3>17. Generics Pattern</h3><p>Generics allow us to build reusable components while retaining type information.</p><p>Instead of:</p><pre>function identity(value: any): any {<br>  return value;<br>}</pre><p>use:</p><pre>function identity&lt;T&gt;(value: T): T {<br>  return value;<br>}</pre><p>Now:</p><pre>const a = identity(&quot;hello&quot;);<br>// string<br><br>const b = identity(100);<br>// number</pre><p>The important part is that the relationship is preserved:</p><pre>Input T<br>  │<br>  ▼<br>Function&lt;T&gt;<br>  │<br>  ▼<br>Output T</pre><h3>Generic API response</h3><pre>interface ApiResponse&lt;T&gt; {<br>  data: T;<br>  status: number;<br>  message: string;<br>}</pre><p>Then:</p><pre>type UserResponse =<br>  ApiResponse&lt;User&gt;;<br><br>type ProductResponse =<br>  ApiResponse&lt;Product&gt;;</pre><p>One contract.</p><p>Multiple strongly typed data models.</p><h3>18. Generic Constraints</h3><p>Sometimes T needs to satisfy a requirement.</p><p>This won’t work:</p><pre>function getId&lt;T&gt;(item: T) {<br>  return item.id;<br>}</pre><p>because TypeScript doesn’t know whether T contains id.</p><p>Instead:</p><pre>function getId&lt;T extends { id: string }&gt;(<br>  item: T<br>) {<br>  return item.id;<br>}</pre><p>Now:</p><pre>getId({<br>  id: &quot;123&quot;,<br>  name: &quot;Hareesh&quot;<br>});</pre><p>works.</p><p>The constraint says:</p><pre>T can be anything<br>BUT<br>T must have id: string</pre><h3>19. keyof Pattern</h3><p>Given:</p><pre>interface User {<br>  id: string;<br>  name: string;<br>  age: number;<br>}</pre><p>Then:</p><pre>type UserKey = keyof User;</pre><p>becomes:</p><pre>&quot;id&quot; | &quot;name&quot; | &quot;age&quot;</pre><p>Now we can build a type-safe property accessor:</p><pre>function getProperty&lt;T, K extends keyof T&gt;(<br>  object: T,<br>  key: K<br>): T[K] {<br>  return object[key];<br>}</pre><p>Usage:</p><pre>const user = {<br>  id: &quot;1&quot;,<br>  name: &quot;Hareesh&quot;,<br>  age: 30<br>};<br><br>getProperty(user, &quot;name&quot;);</pre><p>This is allowed:</p><pre>getProperty(user, &quot;name&quot;);</pre><p>This is rejected:</p><pre>getProperty(user, &quot;salary&quot;);</pre><p>That’s the power of connecting:</p><pre>Generics<br>   +<br>keyof<br>   +<br>Indexed Access</pre><h3>20. Mapped Types</h3><p>Mapped types let us transform existing types.</p><p>Given:</p><pre>interface User {<br>  id: string;<br>  name: string;<br>  email: string;<br>}</pre><p>We can create:</p><pre>type OptionalUser = {<br>  [K in keyof User]?: User[K];<br>};</pre><p>Equivalent conceptually to:</p><pre>{<br>  id?: string;<br>  name?: string;<br>  email?: string;<br>}</pre><p>This is the foundation behind many powerful TypeScript utility types.</p><h3>21. Conditional Types</h3><p>Conditional types allow the type system to make decisions.</p><p>The basic form:</p><pre>T extends U ? X : Y</pre><p>Example:</p><pre>type Flatten&lt;T&gt; =<br>  T extends Array&lt;infer U&gt;<br>    ? U<br>    : T;</pre><p>Then:</p><pre>type A = Flatten&lt;string[]&gt;;<br>// string<br><br>type B = Flatten&lt;number&gt;;<br>// number</pre><p>This is where TypeScript starts behaving almost like a small compile-time programming language.</p><p>But this power should be used carefully.</p><h3>22. infer Pattern</h3><p>infer lets TypeScript extract a type from another type.</p><p>For example:</p><pre>type MyReturnType&lt;T&gt; =<br>  T extends (...args: any[]) =&gt; infer R<br>    ? R<br>    : never;</pre><p>Then:</p><pre>function getUser() {<br>  return {<br>    id: &quot;1&quot;,<br>    name: &quot;Hareesh&quot;<br>  };<br>}<br><br>type User = MyReturnType&lt;typeof getUser&gt;;</pre><p>The compiler derives the return type automatically.</p><p>This technique appears heavily in advanced libraries and framework type definitions.</p><h3>23. Utility Type Pattern</h3><p>Before writing your own advanced utility types, know the built-in ones:</p><pre>Partial<br>Required<br>Readonly<br>Pick<br>Omit<br>Record<br>Exclude<br>Extract<br>NonNullable<br>ReturnType<br>Parameters<br>InstanceType<br>Awaited</pre><p>Example:</p><pre>interface User {<br>  id: string;<br>  name: string;<br>  email: string;<br>  password: string;<br>}<br><br>type PublicUser =<br>  Omit&lt;User, &quot;password&quot;&gt;;</pre><p>This is preferable to duplicating the entire interface.</p><h3>24. Record Pattern</h3><p>Record is extremely useful for maps and configuration objects.</p><pre>type Permission =<br>  &quot;read&quot; |<br>  &quot;write&quot; |<br>  &quot;delete&quot;;<br><br>type PermissionMap =<br>  Record&lt;Permission, boolean&gt;;</pre><p>Now:</p><pre>const permissions: PermissionMap = {<br>  read: true,<br>  write: false,<br>  delete: false<br>};</pre><p>If someone forgets a permission, TypeScript can tell us.</p><p>This is much safer than:</p><pre>const permissions: Record&lt;string, boolean&gt;</pre><p>because Record&lt;string, boolean&gt; accepts essentially any string key.</p><h3>25. Branded Types</h3><p>This pattern solves a subtle problem.</p><p>These two values are both strings:</p><pre>const userId: string;<br>const productId: string;</pre><p>But semantically they are different.</p><p>Create branded types:</p><pre>type UserId =<br>  string &amp; {<br>    readonly __brand: &quot;UserId&quot;;<br>  };<br><br>type ProductId =<br>  string &amp; {<br>    readonly __brand: &quot;ProductId&quot;;<br>  };</pre><p>Now:</p><pre>function getUser(id: UserId) {}<br><br>function getProduct(id: ProductId) {}</pre><p>The compiler can help prevent accidental mixing.</p><h3>Think of it as:</h3><pre>string<br>  │<br>  ├── UserId<br>  ├── ProductId<br>  ├── OrderId<br>  └── TransactionId</pre><p>This becomes particularly valuable in large systems where many domain identifiers share the same primitive type.</p><h3>26. Type Guard Pattern</h3><p>Sometimes data enters your application as unknown.</p><p>For example:</p><pre>const data: unknown = await response.json();</pre><p>Don’t immediately do:</p><pre>const user = data as User;</pre><p>Instead, validate/narrow it.</p><pre>function isUser(<br>  value: unknown<br>): value is User {<br>  return (<br>    typeof value === &quot;object&quot; &amp;&amp;<br>    value !== null &amp;&amp;<br>    &quot;id&quot; in value &amp;&amp;<br>    &quot;name&quot; in value<br>  );<br>}</pre><p>Then:</p><pre>if (isUser(data)) {<br>  console.log(data.name);<br>}</pre><h3>Important distinction</h3><p>TypeScript types disappear at runtime.</p><p>So:</p><pre>interface User {<br>  id: string;<br>}</pre><p>doesn’t validate API data.</p><p>For untrusted runtime data, combine TypeScript with runtime validation when appropriate.</p><h3>27. Exhaustive Checking</h3><p>One of the strongest combinations is:</p><pre>Discriminated Union<br>        +<br>never<br>        +<br>switch</pre><p>Example:</p><pre>type Status =<br>  | &quot;loading&quot;<br>  | &quot;success&quot;<br>  | &quot;error&quot;;</pre><p>Helper:</p><pre>function assertNever(<br>  value: never<br>): never {<br>  throw new Error(<br>    `Unexpected value: ${value}`<br>  );<br>}</pre><p>Then:</p><pre>function render(status: Status) {<br>  switch (status) {<br>    case &quot;loading&quot;:<br>      return &quot;Loading&quot;;<br>    case &quot;success&quot;:<br>      return &quot;Success&quot;;<br>    case &quot;error&quot;:<br>      return &quot;Error&quot;;<br>    default:<br>      return assertNever(status);<br>  }<br>}</pre><pre>Now imagine someone adds:&quot;cancelled&quot; to Status.</pre><p>The compiler can expose the missing branch.</p><h3>This is one of the places where the compiler becomes a design-review tool.</h3><h3>28. Template Literal Types</h3><p>TypeScript can generate string types from other types.</p><pre>type Entity =<br>  &quot;user&quot; |<br>  &quot;order&quot; |<br>  &quot;product&quot;;<br><br>type Event =<br>  `${Entity}:created` |<br>  `${Entity}:updated` |<br>  `${Entity}:deleted`;</pre><p>Now valid values include:</p><pre>user:created<br>user:updated<br>user:deleted<br><br>order:created<br>order:updated<br>order:deleted<br><br>product:created<br>product:updated<br>product:deleted</pre><p>This can be useful for:</p><ul><li>event systems</li><li>analytics events</li><li>permissions</li><li>routes</li><li>feature flags</li><li>design systems</li></ul><h3>29. as const Pattern</h3><p>Consider:</p><pre>const roles = [<br>  &quot;admin&quot;,<br>  &quot;editor&quot;,<br>  &quot;viewer&quot;<br>];</pre><p>The inferred type is generally an array of strings.</p><p>But:</p><pre>const roles = [<br>  &quot;admin&quot;,<br>  &quot;editor&quot;,<br>  &quot;viewer&quot;<br>] as const;</pre><p>gives us a readonly tuple with literal values.</p><p>Then:</p><pre>type Role =<br>  typeof roles[number];<br><br>becomes:<br><br><br>&quot;admin&quot; |<br>&quot;editor&quot; |<br>&quot;viewer&quot;</pre><p>This is an excellent pattern when values are the source of truth.</p><h3>30. satisfies Pattern</h3><p>satisfies is particularly useful for configuration.</p><pre>type Config = {<br>  retries: number;<br>  environment:<br>    | &quot;development&quot;<br>    | &quot;production&quot;;<br>};<br><br>const config = {<br>  retries: 3,<br>  environment: &quot;production&quot;<br>} satisfies Config;</pre><p>The object is checked against the contract while retaining useful inference.</p><p>This is particularly useful for:</p><ul><li>route configuration</li><li>feature flags</li><li>design tokens</li><li>static configuration</li><li>permission maps</li></ul><h3>31. Dependency Injection</h3><p>Instead of creating dependencies inside a class:</p><pre>class UserService {<br>  private api = new ApiClient();<br>}</pre><p>inject the dependency:</p><pre>class UserService {<br>  constructor(<br>    private readonly api: ApiClient<br>  ) {}<br>}</pre><p>Production:</p><pre>const service =<br>  new UserService(apiClient);</pre><p>Testing:</p><pre>const service =<br>  new UserService(mockApiClient);</pre><h3>Diagram</h3><pre>                UserService<br>                      ▲<br>                      │<br>                 Dependency<br>                      │<br>             ┌────────┴────────┐<br>             ▼                 ▼<br>        ApiClient         MockApiClient<br>       Production            Testing</pre><p>This is one of the simplest ways to make code easier to test.</p><h3>32. State Pattern vs Discriminated Union</h3><p>These are often confused.</p><p>Suppose you have:</p><pre>Draft<br>Paid<br>Shipped<br>Cancelled</pre><p>A discriminated union might be enough:</p><pre>type Order =<br>  | { status: &quot;draft&quot; }<br>  | { status: &quot;paid&quot; }<br>  | { status: &quot;shipped&quot; }<br>  | { status: &quot;cancelled&quot; };</pre><p>But if every state has significant behavior:</p><pre>Draft<br> ├── edit()<br> ├── submit()<br><br>Paid<br> ├── refund()<br> ├── ship()<br>Shipped<br> ├── track()<br> └── deliver()</pre><p>then a State Pattern may be more appropriate.</p><blockquote>The lesson</blockquote><p>Don’t choose based on terminology.</p><p>Choose based on complexity.</p><h3>33. Strategy vs State</h3><p>Another common interview question.</p><blockquote>Strategy</blockquote><p>The client chooses an algorithm.</p><pre>Order<br>  │<br>  ▼<br>Strategy<br>  ├── CreditCard<br>  ├── PayPal<br>  └── UPI</pre><h3>State</h3><p>The object’s behavior changes according to its current state.</p><pre>Order<br>  │<br>  ├── Draft<br>  ├── Paid<br>  └── Shipped</pre><p>Simple distinction:</p><blockquote><strong><em>Strategy changes how something is done.</em></strong></blockquote><blockquote><strong><em>State changes how an object behaves based on where it is in its lifecycle.</em></strong></blockquote><h3>34. Factory vs Strategy</h3><p>Another important distinction.</p><h3>Factory</h3><p>Answers:</p><blockquote><strong><em>Which object should I create?</em></strong></blockquote><pre>PaymentFactory.create(&quot;stripe&quot;);</pre><h3>Strategy</h3><p>Answers:</p><blockquote><strong><em>Which algorithm/behavior should I use?</em></strong></blockquote><pre>new Order(discountStrategy);</pre><p>They can also work together:</p><pre>Factory<br>   ↓<br>creates<br>   ↓<br>Strategy<br>   ↓<br>executes behavior</pre><h3>35. TypeScript Patterns in React</h3><p>These patterns become especially powerful in React.</p><h3>Variant-based component props</h3><p>Instead of:</p><pre>interface ButtonProps {<br>  primary?: boolean;<br>  danger?: boolean;<br>  loading?: boolean;<br>}</pre><p>you can model variants:</p><pre>type ButtonProps =<br>  | {<br>      variant: &quot;primary&quot;;<br>      loading?: boolean;<br>    }<br>  | {<br>      variant: &quot;danger&quot;;<br>      confirmationRequired: boolean;<br>    };</pre><p>Now TypeScript can enforce different requirements for different variants.</p><h3>36. Type-Safe Component APIs</h3><p>Suppose a component supports:</p><pre>Link<br>Button</pre><p>Instead of allowing invalid combinations:</p><pre>{<br>  href?: string;<br>  onClick?: () =&gt; void;<br>}<br><br>use:<br>type ActionProps =<br>  | {<br>      type: &quot;link&quot;;<br>      href: string;<br>    }<br>  | {<br>      type: &quot;button&quot;;<br>      onClick: () =&gt; void;<br>    };<br><br><br>Now:<br><br>&lt;Action<br>  type=&quot;link&quot;<br>  href=&quot;/users&quot;<br>/&gt;</pre><p>is valid.</p><p>But:</p><pre>&lt;Action<br>  type=&quot;link&quot;<br>  onClick={...}<br>/&gt;</pre><p>can be rejected.</p><p>This is how TypeScript can become part of your component architecture.</p><h3>37. Type-Safe Event Systems</h3><p>Suppose:</p><pre>type Events = {<br>  &quot;user:created&quot;: User;<br>  &quot;user:deleted&quot;: UserId;<br>  &quot;order:created&quot;: Order;<br>};</pre><p>We can build:</p><pre>class EventBus&lt;T extends Record&lt;string, unknown&gt;&gt; {<br>  on&lt;K extends keyof T&gt;(<br>    event: K,<br>    handler: (data: T[K]) =&gt; void<br>  ) {<br>    // implementation<br>  }<br><br>emit&lt;K extends keyof T&gt;(<br>    event: K,<br>    data: T[K]<br>  ) {<br>    // implementation<br>  }<br>}</pre><p>Now:</p><pre>bus.emit(&quot;user:created&quot;, user);</pre><p>is valid.</p><p>But:</p><pre>bus.emit(&quot;user:created&quot;, order);</pre><p>is rejected.</p><p>This is a powerful example of combining:</p><pre>Generics<br>+<br>keyof<br>+<br>Indexed Access<br>+<br>Mapped Type thinking</pre><h3>38. Type-Safe API Layer</h3><p>A mature frontend application can use:</p><pre>Component<br>     ↓<br>Hook<br>     ↓<br>Service<br>     ↓<br>Repository<br>     ↓<br>API Client<br>     ↓<br>HTTP</pre><p>with types flowing through the entire pipeline.</p><p>For example:</p><pre>type ApiResponse&lt;T&gt; = {<br>  data: T;<br>  status: number;<br>};<br><br>interface UserRepository {<br>  getUser(id: UserId):<br>    Promise&lt;Result&lt;User, ApiError&gt;&gt;;<br>}</pre><p>Now your component isn’t dealing with:</p><pre>any</pre><p>at every layer.</p><p>Instead, the architecture itself communicates the contract.</p><h3>39. The Most Important Anti-Patterns</h3><p>Knowing what <strong>not</strong> to do is just as important.</p><h3>Anti-pattern 1 — any everywhere</h3><pre>function process(data: any) {}</pre><p>This removes much of the benefit of TypeScript.</p><p>Prefer:</p><pre>function process(data: unknown) {}</pre><p>and narrow it.</p><h3>Anti-pattern 2 — Overusing type assertions</h3><p>This:</p><pre>const user =<br>  response.data as User;</pre><p>doesn’t validate the data.</p><p>It only tells the compiler:</p><blockquote><em>“Trust me.”</em></blockquote><p>Use runtime validation when data is untrusted.</p><h3>Anti-pattern 3 — Generic for the sake of generic</h3><p>Don’t write:</p><pre>function transform&lt;<br>  T,<br>  U,<br>  V,<br>  R<br>&gt;(...) {}</pre><p>unless the relationships between those types actually matter.</p><h3>Anti-pattern 4 — Giant union types</h3><p>Discriminated unions are powerful, but a 100-member union can become difficult to maintain.</p><p>Sometimes the domain needs a different abstraction.</p><h3>Anti-pattern 5 — Type-level cleverness</h3><p>If your type definition is harder to understand than your business logic, stop and reconsider.</p><pre>Type complexity<br>       │<br>       ▼<br>Developer complexity<br>       │<br>       ▼<br>Maintenance cost</pre><p>Type safety has a cost.</p><p>The goal is not maximum type complexity.</p><p>The goal is <strong>maximum useful safety</strong>.</p><h3>40. The Pattern Decision Matrix</h3><p>When you face a problem, this is the mental model I’d use.</p><pre>PROBLEM<br>   │<br>   ├── Need to create objects?<br>   │       ├── Simple creation → Constructor<br>   │       ├── Complex creation → Builder<br>   │       ├── Multiple implementations → Factory<br>   │       └── Families of objects → Abstract Factory<br>   │<br>   ├── Need to integrate another system?<br>   │       └── Adapter<br>   │<br>   ├── Complex subsystem?<br>   │       └── Facade<br>   │<br>   ├── Add behavior without modifying object?<br>   │       └── Decorator<br>   │<br>   ├── Multiple interchangeable algorithms?<br>   │       └── Strategy<br>   │<br>   ├── Subscribers react to changes?<br>   │       └── Observer<br>   │<br>   ├── Need actions/history/undo?<br>   │       └── Command<br>   │<br>   ├── Data-access abstraction?<br>   │       └── Repository<br>   │<br>   ├── Complex state lifecycle?<br>   │       └── State / Discriminated Union<br>   │<br>   └── Type-level problem?<br>           ├── Reuse → Generics<br>           ├── Transform → Mapped Types<br>           ├── Decision → Conditional Types<br>           ├── Extract → infer<br>           ├── Property safety → keyof<br>           ├── Literal safety → as const<br>           ├── Contract validation → satisfies<br>           └── Domain safety → Branded Types</pre><h3>41. What I Would Prioritize as a Senior Frontend Developer</h3><p>If you’re preparing for a senior or lead frontend interview, don’t try to memorize every Gang of Four pattern.</p><p>I’d prioritize these:</p><h3>Tier 1 — Must Know</h3><pre>Discriminated Unions<br>Generics<br>Type Guards<br>keyof<br>Mapped Types<br>Utility Types<br>Composition<br>Strategy<br>Repository<br>Factory</pre><h3>Tier 2 — Strongly Recommended</h3><pre>Result Type<br>Branded Types<br>Conditional Types<br>infer<br>Exhaustive Checking<br>Dependency Injection<br>Adapter<br>Facade<br>Observer<br>Decorator</pre><h3>Tier 3 — Understand the Concept</h3><pre>Builder<br>Command<br>State<br>Abstract Factory<br>Singleton</pre><p>The reason is simple:</p><p>A frontend developer is much more likely to use:</p><pre>Generics<br>+<br>Discriminated Unions<br>+<br>Composition<br>+<br>Strategy<br>+<br>Repository</pre><p>than to implement a textbook Abstract Factory.</p><h3>42. 10+ Years of Experience: What Changes?</h3><p>When you’re early in your career, the question is often:</p><blockquote><em>“Which pattern should I use?”</em></blockquote><p>After years of working with large applications, the question changes to:</p><blockquote><em>“What is the smallest abstraction that solves this problem without making the system harder to understand?”</em></blockquote><p>That distinction is huge.</p><p>For example:</p><h3>Junior approach</h3><pre>Problem<br>  ↓<br>Pattern<br>  ↓<br>More classes<br>  ↓<br>More abstractions</pre><h3>Mature approach</h3><pre>Problem<br>  ↓<br>Understand volatility<br>  ↓<br>Identify boundary<br>  ↓<br>Start simple<br>  ↓<br>Introduce abstraction only where repetition/change justifies it</pre><p>Patterns should emerge from the architecture.</p><p>They shouldn’t be forced into it.</p><h3>43. Questions I Would Ask in a 10+ Year Interview</h3><p>These are much more interesting than:</p><blockquote><em>“What is Factory Pattern?”</em></blockquote><h3>Architecture</h3><p><strong>1. You have a 2,000-line React component. How would you identify which pattern or abstraction to introduce?</strong></p><p><strong>2. When would you reject a design pattern even though it appears to fit?</strong></p><p><strong>3. How do you identify whether an abstraction is premature?</strong></p><p><strong>4. When would you prefer composition over inheritance?</strong></p><p><strong>5. How would you prevent Singleton from becoming global mutable state?</strong></p><h3>TypeScript</h3><p><strong>6. How would you model an API with loading, success, error and retry states?</strong></p><p><strong>7. How would you prevent invalid combinations of React props?</strong></p><p><strong>8. Explain the difference between </strong><strong>unknown, </strong><strong>any, and </strong><strong>never.</strong></p><p><strong>9. When would you use </strong><strong>type versus </strong><strong>interface?</strong></p><p><strong>10. How does </strong><strong>keyof work with generics?</strong></p><h3>Advanced TypeScript</h3><p><strong>11. Explain a real use case for conditional types.</strong></p><p><strong>12. What does </strong><strong>infer do?</strong></p><p><strong>13. What is a mapped type?</strong></p><p><strong>14. What are distributive conditional types?</strong></p><p><strong>15. When would you use branded types?</strong></p><p><strong>16. What problem does </strong><strong>satisfies solve?</strong></p><p><strong>17. How does </strong><strong>as const change inference?</strong></p><h3>Real-World Design</h3><p><strong>18. Design a type-safe event bus.</strong></p><p><strong>19. Design a type-safe API client.</strong></p><p><strong>20. Design a permission system using TypeScript.</strong></p><p><strong>21. Design a payment provider abstraction supporting Stripe, PayPal and another provider.</strong></p><p><strong>22. How would you introduce a Repository Pattern into an existing React application without rewriting everything?</strong></p><p><strong>23. How would you model WebSocket events with different payloads?</strong></p><p><strong>24. How would you prevent a </strong><strong>ProductId from being passed to a function requiring </strong><strong>UserId?</strong></p><h3>44. The Question That Separates Senior Developers</h3><p>One question I particularly like:</p><blockquote><strong><em>“Tell me about a time when you deliberately did NOT use a design pattern.”</em></strong></blockquote><p>A strong answer isn’t:</p><blockquote><em>“I don’t like design patterns.”</em></blockquote><p>A strong answer sounds more like:</p><blockquote><em>“The pattern technically fit, but the domain had only one implementation and the abstraction wasn’t protecting against a likely change. Introducing it would have added indirection without reducing complexity. I kept the implementation simple and waited until the second use case justified the abstraction.”</em></blockquote><p>That’s engineering maturity.</p><h3>45. Final Mental Model</h3><p>If you remember only one diagram from this article, remember this:</p><pre>                 BUSINESS PROBLEM<br>                        │<br>                        ▼<br>                Identify Complexity<br>                        │<br>                        ▼<br>             What is likely to change?<br>                        │<br>             ┌──────────┴──────────┐<br>             ▼                     ▼<br>          Behavior              Structure<br>             │                     │<br>        Strategy/State       Adapter/Facade<br>             │                     │<br>             └──────────┬──────────┘<br>                        ▼<br>                   Type Safety<br>                        │<br>        ┌───────────────┼────────────────┐<br>        ▼               ▼                ▼<br>     Generics        Unions           Utilities<br>        │               │                │<br>        ▼               ▼                ▼<br>     keyof          Result Type      Mapped Types<br>     infer          State Model      Conditional<br>     satisfies      Exhaustive       Record<br>        │               │                │<br>        └───────────────┼────────────────┘<br>                        ▼<br>                 SIMPLEER CODE</pre><h3>Final Takeaway</h3><p>After 10+ years of working with frontend architecture, I don’t consider design patterns a checklist.</p><p>They’re a vocabulary.</p><p>They help us communicate:</p><blockquote><em>“This is a Factory.”</em></blockquote><blockquote><em>“This should be an Adapter.”</em></blockquote><blockquote><em>“These behaviors are interchangeable, so Strategy makes sense.”</em></blockquote><blockquote><em>“These states should be represented as a discriminated union.”</em></blockquote><blockquote><em>“These IDs have different domain meanings, so let’s brand them.”</em></blockquote><blockquote><em>“This abstraction isn’t earning its complexity yet.”</em></blockquote><p>And that last one is perhaps the most important.</p><p><strong>Good TypeScript isn’t about writing the most sophisticated types.</strong></p><p>It’s about creating a system where:</p><pre>Invalid states<br>     ↓<br>become difficult to represent<br><br>Changing implementations<br>     ↓<br>don&#39;t break consumers<br>Business rules<br>     ↓<br>are visible in the types<br>Shared behavior<br>     ↓<br>is reusable without duplication<br>Complexity<br>     ↓<br>is isolated behind clear boundaries</pre><p>The ultimate goal isn’t to impress the compiler.</p><p>The goal is to make the <strong>next six months of development easier than the previous six months</strong>.</p><p>That’s where TypeScript patterns become genuinely valuable.</p><h3>One Last Principle</h3><blockquote><strong><em>Don’t ask, “Which TypeScript pattern should I use?”</em></strong></blockquote><blockquote><em>Ask, </em><strong><em>“What complexity am I trying to remove?”</em></strong></blockquote><blockquote><em>Then choose the simplest pattern that actually removes it.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f89f025cba8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LocalStorage vs Cookies: What Should You Actually Use?]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/localstorage-vs-cookies-what-should-you-actually-use-7cad30c20f81?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cad30c20f81</guid>
            <category><![CDATA[frontend-interviews]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-security]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 15:57:08 GMT</pubDate>
            <atom:updated>2026-08-24T15:57:08.149Z</atom:updated>
            <content:encoded><![CDATA[<h3>Security, Authentication, Performance, Browser Behavior, Real-World Use Cases, and Common Mistakes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xw8LB7QRqRaEWWulxIjmVQ.png" /></figure><blockquote><strong><em>One of the most common frontend questions is:</em></strong><em><br></em>“Should I store this data in localStorage or in a cookie?”</blockquote><blockquote><em>After 10+ years of working with frontend applications, I’ve learned that this is rarely a simple storage question.</em></blockquote><blockquote><em>It is primarily a question of </em><strong><em>security, data ownership, browser behavior, server communication, and application architecture</em></strong><em>.</em></blockquote><h3>1. The Short Answer</h3><p>Before going deep, here is the practical rule I use:</p><pre>Need the browser only?<br>        ↓<br>   localStorage<br>        ↓<br>Non-sensitive client-side data</pre><p>Whereas:</p><pre>Need the server to receive it automatically?<br>        ↓<br>      Cookie<br>        ↓<br>Authentication / session / server-required data</pre><p>But there is an important security distinction:</p><pre>Sensitive authentication token<br>        ↓<br>Prefer<br>        ↓<br>HttpOnly + Secure + appropriately configured SameSite cookie</pre><p><strong>Do not blindly put authentication tokens into localStorage just because it is easy to access from JavaScript.</strong></p><h3>2. What Is localStorage?</h3><p>localStorage is a browser-provided Web Storage API that allows JavaScript to store key-value data.</p><p>Example:</p><pre>localStorage.setItem(&quot;theme&quot;, &quot;dark&quot;);<br>const theme = localStorage.getItem(&quot;theme&quot;);<br>console.log(theme);</pre><p>Removing data:</p><pre>localStorage.removeItem(&quot;theme&quot;);</pre><p>Clearing everything for the origin:</p><pre>localStorage.clear();</pre><p>The important point is:</p><blockquote><em>localStorage is primarily a </em><strong><em>client-side storage mechanism</em></strong><em>.</em></blockquote><p>The browser does not automatically attach localStorage values to every HTTP request.</p><h3>3. What Are Cookies?</h3><p>Cookies are small pieces of data associated with a website/domain.</p><p>A server can send a cookie using:</p><pre>Set-Cookie: sessionId=abc123</pre><p>The browser stores it.</p><p>For subsequent matching requests, the browser can automatically send it:</p><pre>Cookie: sessionId=abc123</pre><p>This makes cookies fundamentally different from localStorage.</p><h3>4. The Most Important Architectural Difference</h3><p>This is the diagram I keep in mind when deciding between them.</p><blockquote>localStorage</blockquote><pre>Browser<br>        ┌──────────────────┐<br>        │                  │<br>        │   React / JS     │<br>        │       │          │<br>        │       ▼          │<br>        │  localStorage    │<br>        │       │          │<br>        │       X          │<br>        │   Not automatically<br>        │   sent with HTTP │<br>        │                  │<br>        └──────────────────┘<br>                 │<br>                 │ fetch()<br>                 ▼<br>              Server</pre><p>Your JavaScript has to explicitly read the value:</p><pre>const token = localStorage.getItem(&quot;token&quot;);<br>fetch(&quot;/api/profile&quot;, {<br>  headers: {<br>    Authorization: `Bearer ${token}`<br>  }<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JPtUvszkrxJFQ8G_" /></figure><h3>5. Cookies Work Differently</h3><pre>Browser<br>   │<br>   │ HTTP Request<br>   │<br>   │ Cookie: sessionId=abc123<br>   ▼<br>Server<br>   │<br>   │ Response<br>   │<br>   │ Set-Cookie: sessionId=xyz789<br>   ▼<br>Browser</pre><p>The browser manages the cookie according to its attributes and request context.</p><p>That is why cookies are heavily used for:</p><ul><li>Sessions</li><li>Authentication</li><li>Server-side state</li><li>Security-related browser behavior</li></ul><h3>6. localStorage vs Cookies</h3><p>┌────────────────────────────┬──────────────────────────────┬──────────────────────────────┐<br>│ Feature │ localStorage │ Cookies │<br>├────────────────────────────┼──────────────────────────────┼──────────────────────────────┤<br>│ Storage location │ Browser │ Browser │<br>│ JavaScript access │ Yes │ Usually yes, unless HttpOnly │<br>│ Server receives │ No │ Yes, when applicable │<br>│ Storage capacity │ Larger than cookies │ Much smaller │<br>│ Expiration │ No built-in expiration │ Supports expiration │<br>│ HttpOnly │ No │ Yes │<br>│ Secure attribute │ No │ Yes │<br>│ SameSite │ No │ Yes │<br>│ Best for │ Client-side preferences/ │ Sessions, auth, and │<br>│ │ state │ server-required data │<br>│ Sent with every request │ No │ Can be │<br>│ XSS exposure │ Accessible to JavaScript │ HttpOnly cookies are not │<br>│ │ │ readable by JavaScript │<br>│ Server-controlled │ No │ Yes │<br>│ Request overhead │ No automatic overhead │ Can increase request size │<br>└────────────────────────────┴──────────────────────────────┴──────────────────────────────┘</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l-GlEChUX-75Qg1v" /></figure><h3>7. The Biggest Security Difference</h3><p>This is where the discussion becomes more important than simply comparing storage APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pqbFXfvpnnNQ_Qg5" /></figure><p>Suppose you store:</p><pre>localStorage.setItem(<br>  &quot;accessToken&quot;,<br>  &quot;abc123&quot;<br>);</pre><p>Your JavaScript can read it:</p><pre>const token = localStorage.getItem(&quot;accessToken&quot;);</pre><p>That means if an attacker manages to execute malicious JavaScript in your application through an XSS vulnerability, the token may be accessible to that script.</p><p>Conceptually:</p><pre>XSS<br> │<br> ▼<br>Malicious JavaScript<br> │<br> ▼<br>localStorage.getItem(&quot;accessToken&quot;)<br> │<br> ▼<br>Token exposed</pre><p>This is one of the major reasons I avoid storing sensitive authentication credentials in localStorage when a safer architecture is available.</p><h3>8. HttpOnly Cookies Change the Situation</h3><p>Consider:</p><pre>Set-Cookie:<br>sessionId=abc123;<br>HttpOnly;<br>Secure;<br>SameSite=Lax</pre><p>HttpOnly means JavaScript cannot access the cookie through:</p><pre>document.cookie</pre><p>So:</p><pre>XSS<br> │<br> ▼<br>JavaScript<br> │<br> ├── localStorage → accessible<br> │<br> └── HttpOnly cookie → inaccessible</pre><p>This doesn’t mean cookies magically eliminate XSS.</p><p>The attacker may still perform actions through the victim’s browser if your application is vulnerable.</p><p>But HttpOnly can prevent JavaScript from directly reading the authentication cookie.</p><h3>9. What Does Secure Mean?</h3><p>A cookie can be configured with:</p><pre>Secure</pre><p>This tells the browser to send it only over secure HTTPS connections, subject to the browser’s cookie rules.</p><p>Example:</p><pre>Set-Cookie:<br>sessionId=abc123;<br>Secure;<br>HttpOnly</pre><p>For production authentication, HTTPS should be considered mandatory.</p><h3>10. What Is SameSite?</h3><p>SameSite controls how cookies behave in cross-site request contexts.</p><p>Common values include:</p><pre>Strict<br>Lax<br>None</pre><p>Example:</p><pre>Set-Cookie:<br>sessionId=abc123;<br>HttpOnly;<br>Secure;<br>SameSite=Lax</pre><p>A simplified view:</p><pre>SameSite=Strict<br>      ↓<br>More restrictive cross-site behavior</pre><pre>SameSite=Lax<br>      ↓<br>Common practical default for many session cookies</pre><pre>SameSite=None<br>      ↓<br>Cross-site cookie usage<br>      +<br>Secure required</pre><p>The exact browser behavior depends on the request context and cookie configuration, so authentication architecture should be tested against the actual deployment scenario.</p><h3>11. What Is Cookie Path?</h3><p>Cookies can be scoped using Path.</p><p>Example:</p><pre>Set-Cookie:<br>sessionId=abc123;<br>Path=/</pre><p>This makes the cookie available to requests under that path.</p><p>For example:</p><pre>Path=/<br>├── /dashboard<br>├── /profile<br>├── /settings<br>└── /orders</pre><p>A narrower path can restrict where the cookie is sent.</p><h3>12. What Is Cookie Domain?</h3><p>Cookies can also have domain-related behavior.</p><p>For example:</p><pre>example.com<br><br>and:<br>api.example.com</pre><p>may require careful cookie-domain configuration depending on your architecture.</p><p>This becomes especially important when working with:</p><ul><li>Multiple subdomains</li><li>Micro-frontends</li><li>API domains</li><li>Authentication domains</li><li>SSO systems</li></ul><h3>13. Authentication: localStorage vs Cookies</h3><p>This is one of the most important real-world decisions.</p><blockquote>Approach A</blockquote><pre>Login<br> ↓<br>Server returns token<br> ↓<br>React<br> ↓<br>localStorage<br> ↓<br>Authorization header</pre><p>Example:</p><pre>localStorage.setItem(<br>  &quot;accessToken&quot;,<br>  token<br>);<br><br>Then:<br><br>fetch(&quot;/api/orders&quot;, {<br>  headers: {<br>    Authorization:<br>      `Bearer ${localStorage.getItem(&quot;accessToken&quot;)}`<br>  }<br>});</pre><p>This is convenient.</p><p>But the token is accessible to JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C7XIXWETy8jjknpt" /></figure><h3>14. Cookie-Based Authentication</h3><p>A common alternative:</p><pre>Login<br>   ↓<br>Server<br>   ↓<br>Set-Cookie<br>   ↓<br>Browser<br>   ↓<br>HttpOnly Cookie</pre><p>Then:</p><pre>Browser<br>   │<br>   │ Cookie automatically attached<br>   ▼<br>API</pre><p>JavaScript doesn’t need to retrieve the authentication cookie.</p><p>This can provide a stronger security posture when configured correctly.</p><h3>15. What I Prefer for Authentication</h3><p>For applications where security matters, I generally prefer an architecture along these lines:</p><pre>                 Login<br>                   │<br>                   ▼<br>                Server<br>                   │<br>                   ▼<br>        HttpOnly + Secure Cookie<br>                   │<br>                   ▼<br>               Browser<br>                   │<br>                   ▼<br>          Authenticated Request<br>                   │<br>                   ▼<br>                Server</pre><p>The exact implementation depends on:</p><ul><li>SPA architecture</li><li>SSR/Next.js</li><li>Backend architecture</li><li>OAuth/OIDC provider</li><li>Same-site vs cross-site deployment</li><li>API gateway</li><li>Domain structure</li></ul><p>There isn’t a universal authentication implementation.</p><h3>16. When localStorage Is Perfectly Fine</h3><p>I don’t avoid local Storage.</p><p>It is excellent for <strong>non-sensitive client-side data</strong>.</p><p>Examples:</p><pre>Theme<br>Language preference<br>UI preferences<br>Sidebar state<br>Recently selected filters<br>Non-sensitive draft data<br>Display preferences<br>Client-only configuration</pre><p>For example:</p><pre>localStorage.setItem(<br>  &quot;theme&quot;,<br>  &quot;dark&quot;<br>);</pre><p>This is a perfectly reasonable use case.</p><h3>17. Real Example: Dark Mode</h3><p>Suppose a user chooses dark mode.</p><pre>localStorage.setItem(<br>  &quot;theme&quot;,<br>  &quot;dark&quot;<br>);</pre><p>When the application starts:</p><pre>const theme =<br>  localStorage.getItem(&quot;theme&quot;) || &quot;light&quot;;</pre><p>Architecture:</p><pre>User<br> ↓<br>Theme Selector<br> ↓<br>React State<br> ↓<br>localStorage<br> ↓<br>Next Visit<br> ↓<br>Restore Theme</pre><p>There is no reason to involve authentication cookies for this.</p><h3>18. Real Example: Language Preference</h3><pre>localStorage.setItem(<br>  &quot;language&quot;,<br>  &quot;en&quot;<br>);</pre><p>Then:</p><pre>const language =<br>  localStorage.getItem(&quot;language&quot;);</pre><p>Again:</p><pre>Non-sensitive<br>Client-only<br>Persistent preference<br>        ↓<br>    localStorage</pre><h3>19. When Cookies Are Better</h3><p>Cookies are useful when the server needs the information automatically.</p><p>Examples include:</p><pre>Session identifier<br>Authentication session<br>Server-side personalization<br>Security-related browser state<br>Server-required preferences</pre><p>Architecture:</p><pre>Browser<br>   │<br>   │ Cookie automatically attached<br>   ▼<br>Backend<br>   │<br>   ├── Authentication<br>   ├── Authorization<br>   └── Session lookup</pre><h3>20. Performance Difference</h3><p>One thing that is often overlooked:</p><p>Cookies can be sent with HTTP requests.</p><p>Suppose you have:</p><pre>100 requests</pre><p>and every request carries unnecessary cookie data.</p><p>That creates additional request overhead.</p><pre><br>Conceptually:<br><br>Cookie<br>   ↓<br>HTTP Request<br>   ↓<br>Server<br><br>Whereas :<br><br>localStorage<br>   ↓<br>Browser only</pre><p>doesn’t automatically increase every request.</p><blockquote>Senior-level lesson</blockquote><blockquote>Don’t put large amounts of unnecessary data into cookies.</blockquote><blockquote>Cookies are not a replacement for a client-side database.</blockquote><h3>21. Storage Size</h3><p>Neither should be treated as unlimited storage.</p><p>Cookies are intentionally small.</p><p>A common rule of thumb is that individual cookies are limited to a few kilobytes, with browser-specific limits and additional domain constraints.</p><p>local Storage generally provides substantially more space than cookies, often around several megabytes per origin, though exact quotas vary by browser and environment.</p><p>The important architectural point is:</p><pre>Cookie<br>→ Small server-related data<br><br>localStorage<br>→ Larger client-side preference/state data</pre><p>For large client-side datasets, consider technologies such as IndexedDB rather than abusing localStorage.</p><h3>22. localStorage Is Synchronous</h3><p>One important engineering detail:</p><pre>localStorage.getItem(&quot;data&quot;);</pre><p>is synchronous.</p><p>For normal small values, this usually isn’t a concern.</p><p>But repeatedly reading/writing large amounts of data during performance-sensitive UI work is not a good architecture.</p><p>For example, avoid patterns like:</p><pre>Every render<br>   ↓<br>Read large localStorage object<br>   ↓<br>JSON.parse()<br>   ↓<br>Transform data<br>   ↓<br>Render</pre><p>Instead:</p><pre>Initialization<br>   ↓<br>Read once<br>   ↓<br>React state<br>   ↓<br>Use state</pre><h3>23. Don’t Store Huge Objects in localStorage</h3><p>A common implementation:</p><pre>localStorage.setItem(<br>  &quot;users&quot;,<br>  JSON.stringify(hugeUserObject)<br>);<br><br>Then:<br><br>const users =<br>  JSON.parse(<br>    localStorage.getItem(&quot;users&quot;)<br>  );</pre><p>This can create:</p><ul><li>Serialization cost</li><li>Parsing cost</li><li>Memory overhead</li><li>Stale data</li><li>Synchronization problems</li><li>Storage management complexity</li></ul><p>For large client-side data, use a more appropriate storage mechanism.</p><h3>24. localStorage Is String-Based</h3><p>Everything is effectively stored as a string.</p><p>This:</p><pre>localStorage.setItem(<br>  &quot;count&quot;,<br>  10<br>);<br>comes back as:<br>&quot;10&quot;</pre><p>For objects:</p><pre>localStorage.setItem(<br>  &quot;user&quot;,<br>  JSON.stringify(user)<br>);</pre><p>Then:</p><pre>const user = JSON.parse(<br>  localStorage.getItem(&quot;user&quot;)<br>);</pre><p>Be careful with:</p><ul><li>null</li><li>malformed JSON</li><li>schema changes</li><li>stale objects</li><li>versioning</li></ul><h3>25. Cookie Example</h3><p>Setting a cookie from JavaScript:</p><pre>document.cookie =<br>  &quot;theme=dark; Max-Age=3600; Path=/; SameSite=Lax&quot;;</pre><p>Reading cookies:</p><pre>console.log(document.cookie);</pre><p>But remember:</p><pre>document.cookie<br>      ↓<br>JavaScript-readable cookies</pre><p>An HttpOnly cookie cannot be accessed this way.</p><h3>26. A More Secure Authentication Cookie</h3><p>A server might issue something conceptually like:</p><pre>Set-Cookie:<br>sessionId=abc123;<br>HttpOnly;<br>Secure;<br>SameSite=Lax;<br>Path=/</pre><p>Each attribute has a purpose:</p><pre>HttpOnly<br>→ JavaScript cannot read it<br><br>Secure<br>→ HTTPS-only transmission<br><br>SameSite<br>→ Controls cross-site cookie behavior<br><br>Path<br>→ Controls applicable request paths</pre><h3>27. The XSS Question</h3><p>This is one of the most common interview questions.</p><h3>Question</h3><blockquote><em>If I store a JWT in localStorage, what happens if my application has XSS?</em></blockquote><p>Potentially:</p><pre>XSS<br> ↓<br>Malicious JavaScript<br> ↓<br>localStorage.getItem(&quot;jwt&quot;)<br> ↓<br>JWT exposed</pre><p>That is why simply saying:</p><blockquote><em>“JWT is secure because it is signed”</em></blockquote><p>is incomplete.</p><p>A signed token can still be stolen.</p><p>The question is not only:</p><pre>Can someone modify the token?</pre><p>It is also:</p><pre>Can someone steal the token?</pre><h3>28. Does HttpOnly Cookie Solve XSS?</h3><p>Not completely.</p><p>This distinction is extremely important.</p><p>An HttpOnly cookie prevents JavaScript from directly reading the cookie.</p><p>But an XSS vulnerability can still allow malicious JavaScript to perform requests from the victim’s browser.</p><p>So:</p><pre>HttpOnly<br>       ↓<br>Protects cookie confidentiality from JS</pre><p>It does <strong>not</strong> mean:</p><pre>HttpOnly<br>       ↓<br>Application is immune to XSS</pre><p>You still need:</p><ul><li>Output encoding</li><li>Safe DOM APIs</li><li>CSP where appropriate</li><li>Dependency hygiene</li><li>Input validation</li><li>Framework security practices</li></ul><h3>29. Cookies and CSRF</h3><p>Cookies introduce another important security consideration.</p><p>Because cookies can be automatically attached to requests, applications using cookie-based authentication should consider CSRF protections.</p><p>Depending on the architecture, this can involve:</p><pre>SameSite<br>CSRF tokens<br>Origin checks<br>Referer checks where appropriate<br>Server-side validation</pre><p>This is one reason authentication architecture should be designed as a complete security model rather than simply choosing a storage location.</p><h3>30. localStorage vs Cookies: Security Model</h3><p>Think about it this way:</p><pre>localStorage : <br><br>JavaScript<br>    │<br>    ▼<br>localStorage<br>    │<br>    ▼<br>Application manually sends data</pre><p>Versus:</p><pre>Cookie : <br><br>Browser<br>    │<br>    ▼<br>Cookie policy<br>    │<br>    ▼<br>HTTP Request<br>    │<br>    ▼<br>Server</pre><p>Cookies provide browser-level controls such as:</p><pre>HttpOnly<br>Secure<br>SameSite<br>Domain<br>Path<br>Expiration</pre><p>That is a major reason they remain important for authentication.</p><h3>31. A Common Mistake</h3><p>I have seen code like this many times:</p><pre>localStorage.setItem(<br>  &quot;username&quot;,<br>  username<br>);<br><br>localStorage.setItem(<br>  &quot;password&quot;,<br>  password<br>);</pre><p>This should never be your authentication strategy.</p><p><strong>Never store a user’s password in localStorage.</strong></p><p>The browser should not be treated as a place to persist raw credentials.</p><h3>32. Another Common Mistake</h3><p>Storing:</p><pre>localStorage.setItem(<br>  &quot;refreshToken&quot;,<br>  refreshToken<br>);</pre><p>without considering the threat model.</p><p>Refresh tokens can be extremely sensitive.</p><p>If the application architecture supports secure HttpOnly cookie-based refresh-token handling, that can provide a stronger security posture.</p><p>Again, the correct solution depends on your authentication architecture.</p><h3>33. What About SessionStorage?</h3><p>Developers often confuse:</p><pre>localStorage<br>sessionStorage<br>cookies</pre><p>A simplified comparison:</p><pre>localStorage<br>→ Persistent client-side storage<br><br>sessionStorage<br>→ Storage associated with a browser tab/session<br><br>cookies<br>→ Browser-managed data that can participate in HTTP requests</pre><p>sessionStorage is useful for temporary tab-specific state.</p><p>Example:</p><pre>sessionStorage.setItem(<br>  &quot;checkoutStep&quot;,<br>  &quot;2&quot;<br>);</pre><h3>34. What About IndexedDB?</h3><p>If you need much larger structured client-side data, localStorage is often not the right tool.</p><p>Consider:</p><pre>localStorage<br>→ Small/simple client-side values<br>IndexedDB<br>→ Larger structured client-side data</pre><p>Examples where IndexedDB can be useful:</p><ul><li>Offline applications</li><li>Large datasets</li><li>Cached application data</li><li>PWA scenarios</li><li>Complex client-side storage</li></ul><h3>35. Real-World Architecture</h3><p>For a modern application, I might structure client storage like this:</p><pre>                Web Application<br>                       │<br>          ┌────────────┼────────────┐<br>          │            │            │<br>          ▼            ▼            ▼<br>     localStorage   Cookies     IndexedDB<br>          │            │            │<br>          │            │            │<br>          ▼            ▼            ▼<br>      UI prefs      Session     Large data<br>      Theme         Auth        Offline cache<br>      Language      Security    Structured data</pre><p>The important part is that each storage mechanism has a job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zcQjMbJYb4G1yK8p" /></figure><h3>36. A Practical Decision Tree</h3><p>When deciding where to store something, I use this thought process:</p><pre>Is the data sensitive?<br>       │<br>       ├── YES<br>       │    ↓<br>       │  Does server need it automatically?<br>       │    │<br>       │    └── YES → Consider secure HttpOnly cookie<br>       │<br>       └── NO<br>            ↓<br>       Is it client-only?<br>            │<br>            └── YES → localStorage may be appropriate</pre><p>Then ask:</p><pre>Does it expire?<br>Does it need to be sent to the server?<br>Does JavaScript need access?<br>Could XSS expose it?<br>Does CSRF matter?<br>How large is it?<br>How long should it live?<br>Is it tab-specific?</pre><h3>37. My Practical Decision Table</h3><p>+ — — — — — — — — — — — — — — — — — — — + — — — — — — — — — — — — — — — — — — — — — — — -+<br>| Requirement | Recommended Approach |<br>+ — — — — — — — — — — — — — — — — — — — + — — — — — — — — — — — — — — — — — — — — — — — -+<br>| Dark/light theme | localStorage |<br>| Language preference | localStorage |<br>| UI preferences | localStorage |<br>| Temporary tab state | sessionStorage |<br>| Large offline dataset | IndexedDB |<br>| Authentication session | Secure HttpOnly cookie |<br>| Refresh token | Secure server-managed architecture, often |<br>| | using an HttpOnly cookie |<br>| Password | Never store |<br>| Sensitive token | Avoid localStorage; prefer safer cookie-based |<br>| | architecture when available |<br>| Server-required session information | Cookie |<br>| Non-sensitive client-only data | localStorage |<br>+ — — — — — — — — — — — — — — — — — — — + — — — — — — — — — — — — — — — — —</p><h3>38. What I Would Do in a React Application</h3><p>For example:</p><pre>React Application<br>│<br>├── Authentication<br>│      │<br>│      └── HttpOnly Cookie<br>│<br>├── Theme<br>│      │<br>│      └── localStorage<br>│<br>├── Language<br>│      │<br>│      └── localStorage<br>│<br>├── Temporary Form State<br>│      │<br>│      └── React State<br>│<br>└── Large Offline Data<br>       │<br>       └── IndexedDB</pre><p>This is much cleaner than:</p><pre>Everything<br>    ↓<br>localStorage</pre><h3>39. Common Mistakes I See</h3><blockquote>Mistake 1: Storing everything in localStorage</blockquote><pre>User<br>Token<br>Permissions<br>API responses<br>Large datasets<br>UI state</pre><p>Not everything belongs there.</p><blockquote>Mistake 2: Storing authentication secrets without considering XSS</blockquote><pre>localStorage.setItem(<br>  &quot;accessToken&quot;,<br>  token<br>);</pre><p>Convenient does not mean safest.</p><blockquote>Mistake 3: Putting too much data into cookies</blockquote><p>Cookies can be attached to requests.</p><p>Large cookies can increase request overhead.</p><blockquote>Mistake 4: Treating HttpOnly as an XSS solution</blockquote><p>It protects cookie access from JavaScript.</p><p>It does not fix the underlying XSS vulnerability.</p><blockquote>Mistake 5: Ignoring SameSite</blockquote><p>Cookie-based authentication requires understanding cross-site behavior.</p><blockquote>Mistake 6: Assuming cookies are always secure</blockquote><p>A cookie without proper attributes can still create security problems.</p><blockquote>Mistake 7: Using localStorage for sensitive information because “it’s frontend”</blockquote><p>Frontend storage should always be treated as potentially accessible to application JavaScript.</p><h3>40. Performance Perspective</h3><p>From a performance perspective:</p><h3>localStorage</h3><pre>JavaScript<br>    ↓<br>Read<br>    ↓<br>Parse<br>    ↓<br>Use</pre><p>It doesn’t automatically add data to every HTTP request.</p><h3>Cookies</h3><pre>Cookie<br>   ↓<br>HTTP Request<br>   ↓<br>Network<br>   ↓<br>Server</pre><p>So excessive cookie data can have network implications.</p><p>But don’t optimize based only on this difference.</p><p>A 500-byte cookie is rarely the bottleneck in a properly designed application.</p><p>A large number of unnecessary cookies across thousands of requests can become meaningful.</p><p><strong>Measure first.</strong></p><h3>41. Browser DevTools: How I Debug These Issues</h3><p>When debugging storage-related issues, I usually start with browser DevTools.</p><p>Check:</p><pre>Application<br> ├── Local Storage<br> ├── Session Storage<br> └── Cookies</pre><p>Then inspect:</p><pre>Network<br> ├── Request Headers<br> ├── Cookie<br> ├── Response Headers<br> └── Set-Cookie</pre><p>This distinction is extremely useful.</p><p>If a cookie is missing, don’t immediately assume the frontend code is broken.</p><p>Check:</p><pre>Domain<br>Path<br>Secure<br>SameSite<br>Expiration<br>Request context</pre><h3>42. Debugging Example</h3><p>Suppose login succeeds:</p><pre>POST /login<br>200 OK</pre><p>But the next request is:</p><pre>GET /profile<br>401 Unauthorized</pre><p>Don’t immediately change React code.</p><p>Inspect:</p><pre>POST /login<br>      ↓<br>Set-Cookie?<br>      ↓<br>Browser accepted cookie?<br>      ↓<br>Correct domain?<br>      ↓<br>Correct path?<br>      ↓<br>Secure connection?<br>      ↓<br>SameSite behavior?<br>      ↓<br>Cookie sent with /profile?</pre><p>This is how senior debugging differs from simply changing code until the error disappears.</p><h3>43. Interview Questions</h3><blockquote>What is the main difference between localStorage and cookies?</blockquote><p><strong>Senior answer:</strong></p><p>localStorage is primarily client-side storage accessed through JavaScript, while cookies are browser-managed data that can automatically participate in HTTP requests and support attributes such as HttpOnly, Secure, and SameSite.</p><blockquote>Why shouldn’t I store an authentication token in localStorage?</blockquote><p>Because JavaScript can access localStorage. If an attacker executes JavaScript through an XSS vulnerability, sensitive tokens stored there may be exposed.</p><blockquote>Why are HttpOnly cookies useful?</blockquote><p>They prevent client-side JavaScript from directly reading the cookie, which reduces the impact of token theft through JavaScript-based access.</p><blockquote>Does HttpOnly prevent XSS?</blockquote><p>No.</p><p>It prevents JavaScript from reading the cookie, but XSS can still execute actions in the user’s browser.</p><blockquote>Are cookies automatically sent with every request?</blockquote><p>Cookies can be automatically sent when the request matches the cookie’s applicable domain/path and browser security policies.</p><blockquote>Why can cookies affect performance?</blockquote><p>Because applicable cookies can be included with HTTP requests, increasing request header size and network overhead.</p><h3>What is SameSite?</h3><p>It controls how cookies behave in cross-site request contexts and is an important part of cookie-based security.</p><blockquote>Should I store passwords in localStorage?</blockquote><p><strong>Absolutely not.</strong></p><p>Passwords should never be persisted in browser storage as part of an application’s authentication strategy.</p><h3>localStorage vs sessionStorage?</h3><pre>localStorage<br>→ Persistent client-side storage<br><br>sessionStorage<br>→ Storage scoped to the browser tab/session</pre><h3>What should I use for large offline data?</h3><p>Consider IndexedDB rather than localStorage.</p><h3>44. Questions I Would Ask in a Senior Frontend Interview</h3><p>If I were interviewing a senior frontend developer, I wouldn’t stop at:</p><blockquote><em>“What is localStorage?”</em></blockquote><p>I’d ask:</p><h3>Scenario 1</h3><blockquote><em>Your application stores JWT tokens in localStorage. What security concerns do you see?</em></blockquote><p>Expected discussion:</p><pre>XSS<br>Token exposure<br>Token lifetime<br>Refresh token strategy<br>HttpOnly cookies<br>CSP<br>Authentication architecture</pre><h3>Scenario 2</h3><blockquote><em>Login works, but after refreshing the browser the user becomes unauthorized. How would you debug it?</em></blockquote><p>Expected approach:</p><pre>Check cookie/storage<br>        ↓<br>Check Network<br>        ↓<br>Check request headers<br>        ↓<br>Check Set-Cookie<br>        ↓<br>Check cookie attributes<br>        ↓<br>Check server session</pre><h3>Scenario 3</h3><blockquote><em>Your API is receiving a huge Cookie header on every request. What would you investigate?</em></blockquote><p>Expected discussion:</p><pre>Cookie size<br>Number of cookies<br>Domain/path scope<br>Unnecessary data<br>Authentication design<br>Request frequency</pre><h3>Scenario 4</h3><blockquote><em>Why not put the access token in localStorage and the refresh token in localStorage too?</em></blockquote><p>A strong answer should discuss the security consequences of exposing both credentials to JavaScript and consider a design that keeps long-lived sensitive credentials out of JavaScript where practical.</p><h3>45. The Senior-Level Mental Model</h3><p>Don’t think:</p><pre>localStorage vs Cookies</pre><p>Think:</p><pre>                 Data<br>                   │<br>       ┌───────────┼───────────┐<br>       │           │           │<br>   Sensitive?   Server needs?  Size?<br>       │           │           │<br>       ▼           ▼           ▼<br>   Security     Request      Storage<br>   model        behavior     mechanism<br>       │           │           │<br>       └───────────┼───────────┘<br>                   ▼<br>             Choose Storage</pre><p>Storage should be an architectural decision.</p><h3>46. Final Recommendation</h3><p>If I had to summarize the entire article in a few rules:</p><h3>Use localStorage for:</h3><pre>✓ Theme<br>✓ Language<br>✓ UI preferences<br>✓ Non-sensitive client state<br>✓ Small client-side persistence</pre><h3>Prefer appropriately configured cookies for:</h3><pre>✓ Authentication sessions<br>✓ Server-required session data<br>✓ Sensitive credentials where cookie-based architecture is appropriate</pre><h3>Consider IndexedDB for:</h3><pre>✓ Large client-side datasets<br>✓ Offline applications<br>✓ Structured browser storage</pre><h3>Never use browser storage for:</h3><pre>✗ User passwords<br>✗ Sensitive secrets without considering the threat model<br>✗ Large datasets that belong in a proper storage mechanism</pre><h3>47. Final Takeaway From 10+ Years of Frontend Development</h3><p>The question isn’t:</p><blockquote><strong><em>“Which one is better — localStorage or cookies?”</em></strong></blockquote><p>That’s the wrong question.</p><p>The better question is:</p><blockquote><strong><em>“Who needs this data, how sensitive is it, how long should it live, and should the browser automatically send it to the server?”</em></strong></blockquote><p>Once you answer those questions, the storage mechanism usually becomes much easier to choose.</p><pre>Client-only + non-sensitive<br>        ↓<br>   localStorage<br><br>Temporary + tab-specific<br>        ↓<br>   sessionStorage<br>Large + structured/offline<br>        ↓<br>     IndexedDB<br>Server-required + authentication/session<br>        ↓<br>Secure cookie architecture</pre><p>After 10+ years of frontend development, one principle has consistently held true:</p><blockquote><strong><em>Don’t choose storage because it is convenient. Choose it based on security, ownership, lifecycle, and how the data flows through your application.</em></strong></blockquote><p>That decision will usually matter much more than the API you use to save the value.x</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cad30c20f81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CORS Deep Dive: From Browser Security to Production Debugging]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/cors-deep-dive-from-browser-security-to-production-debugging-f14d0b7b08d1?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f14d0b7b08d1</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 16:56:41 GMT</pubDate>
            <atom:updated>2026-08-20T16:56:41.530Z</atom:updated>
            <content:encoded><![CDATA[<h3>How CORS Actually Works, Why Postman Doesn’t Show the Same Error, and What 10+ Years of Frontend Experience Taught Me</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*MnLgYPdOW0ZHd7O9" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*AZ9kSja7wF9Pf8jS" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8kmF3w1pHpOymBaT" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*Di5EG9gMC-l0__56" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GXm6J9WH_yqjllik" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fyrpEe7DlqRtOWy-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q_--gyAb0TlkGiCK" /></figure><blockquote><strong><em>“It works in Postman, but it fails in the browser.”</em></strong></blockquote><blockquote><em>If you’ve worked with frontend applications for long enough, you’ve almost certainly heard this sentence.</em></blockquote><p>CORS is one of those topics that looks simple at first:</p><pre>Access-Control-Allow-Origin</pre><p>But once you start dealing with:</p><ul><li>React applications</li><li>authentication</li><li>cookies</li><li>JWT</li><li>custom headers</li><li>OPTIONS</li><li>preflight requests</li><li>proxies</li><li>API gateways</li><li>CDNs</li><li>credentials</li><li>redirects</li><li>production environments</li></ul><p>CORS becomes much more interesting.</p><p>After 10+ years of frontend engineering, I’ve found that the biggest CORS problems don’t come from not knowing the header names.</p><p>They come from misunderstanding <strong>who is enforcing CORS, when it happens, and why Postman behaves differently from a browser.</strong></p><p>This article breaks CORS down from the browser’s point of view and then moves into real production scenarios and senior-level interview questions.</p><h3>1. First: What Exactly Is CORS?</h3><p><strong>CORS = Cross-Origin Resource Sharing.</strong></p><p>It is an HTTP-header-based mechanism that allows a server to tell a browser which other origins are permitted to access its resources. Browsers enforce the same-origin policy for script-initiated requests such as fetch() and XMLHttpRequest. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><p>Consider:</p><pre>Frontend<br>https://app.example.com<br><br>        │ fetch()<br>        ▼<br>Backend<br>https://api.example.com</pre><p>These are different <strong>origins</strong> because the hostnames differ.</p><p>The browser therefore evaluates the cross-origin request according to the browser’s security rules and the server’s CORS response.</p><h3>2. Before CORS: Understand Same-Origin Policy</h3><p>CORS makes much more sense once you understand the <strong>Same-Origin Policy (SOP)</strong>.</p><p>An origin is determined by:</p><pre>Scheme + Host + Port</pre><p>For example:</p><pre>https://example.com:443<br>│       │           │<br>│       │           └── Port<br>│       └────────────── Host<br>└────────────────────── Scheme</pre><p>Two URLs are same-origin only when all three match. (<a href="https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Same-origin_policy?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>Example</h3><p>┌──────────────────────┬───────────────────────────┬──────────────┬──────────────────────┐<br>│ URL A │ URL B │ Same Origin? │ Why │<br>├──────────────────────┼───────────────────────────┼──────────────┼──────────────────────┤<br>│ <a href="https://app.com/a">https://app.com/a</a> │ <a href="https://app.com/b">https://app.com/b</a> │ ✅ Yes │ Only path differs │<br>│ <a href="https://app.com/">https://app.com</a> │ <a href="http://app.com/">http://app.com</a> │ ❌ No │ Scheme differs │<br>│ <a href="https://app.com/">https://app.com</a> │ <a href="https://api.app.com/">https://api.app.com</a> │ ❌ No │ Host differs │<br>│ <a href="https://app.com/">https://app.com</a> │ <a href="https://app.com:8443/">https://app.com:8443</a> │ ❌ No │ Port differs │<br>│ <a href="http://app.com/">http://app.com:80</a> │ <a href="http://app.com/users">http://app.com:80/users</a> │ ✅ Yes │ Same origin │<br>└──────────────────────┴───────────────────────────┴──────────────┴──────────────────────┘</p><p>The <strong>path does not define the origin</strong>.</p><p>That’s a very common interview trap.</p><h3>3. Why Does the Browser Need This Security Model?</h3><p>Imagine you’re logged into:</p><pre>https://bank.example</pre><p>with your bank session cookie.</p><p>Now imagine you visit:</p><pre>https://malicious.example</pre><p>That malicious site could attempt:</p><pre>fetch(&quot;https://bank.example/account&quot;)</pre><p>If browsers freely allowed JavaScript from any website to read responses from any other website, sensitive information could potentially be exposed.</p><p>The same-origin policy helps prevent this kind of cross-origin data access. (<a href="https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Same-origin_policy?utm_source=chatgpt.com">MDN Web Docs</a>)</p><p>So CORS isn’t fundamentally an error mechanism.</p><p>It’s part of the browser’s cross-origin security model.</p><h3>4. The Most Important CORS Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QxesHEGbNZ9l7DCL" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mmqcFoRWjho9H0SB" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*UeIAgVBD_kiP8yI4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*HGZg4cH0SVzK7Dzr" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y2CQ3sy8RDBHEJC1" /></figure><p>Think about CORS like this:</p><pre>┌─────────────────────────────┐<br>│       Browser               │<br>│                             │<br>│  https://app.example.com    │<br>│                             │<br>│       JavaScript            │<br>│           │                 │<br>│           │ fetch()         │<br>│           ▼                 │<br>└───────────┼─────────────────┘<br>            │<br>            │ Origin:<br>            │ https://app.example.com<br>            ▼<br>┌─────────────────────────────┐<br>│       API Server            │<br>│                             │<br>│ https://api.example.com     │<br>│                             │<br>│ Access-Control-Allow-Origin │<br>│ : https://app.example.com   │<br>└───────────┬─────────────────┘<br>            │<br>            │ Response<br>            ▼<br>┌─────────────────────────────┐<br>│         Browser             │<br>│                             │<br>│ CORS policy check           │<br>│           │                 │<br>│       ┌───┴───┐             │<br>│       ▼       ▼             │<br>│     Allow    Block          │<br>└─────────────────────────────┘</pre><p>The important thing:</p><blockquote><strong>CORS is primarily enforced by the browser.</strong></blockquote><p>The server provides the headers that tell the browser whether the cross-origin response may be exposed to frontend JavaScript. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>5. Browser vs Server: Who Does What?</h3><p>This is one of the most important concepts.</p><p>┌────────────────────────┬─────────────────────────────────────────────────────┐<br>│ Component │ Responsibility │<br>├────────────────────────┼─────────────────────────────────────────────────────┤<br>│ Browser │ Enforces Same-Origin Policy and CORS rules │<br>│ Frontend JavaScript │ Initiates fetch() / XHR requests │<br>│ Server │ Returns CORS response headers │<br>│ Browser │ Evaluates the CORS response headers │<br>│ Postman │ Sends HTTP requests without browser CORS rules │<br>│ Proxy │ Can route requests through the same browser origin │<br>└────────────────────────┴─────────────────────────────────────────────────────┘</p><p>So when someone says:</p><blockquote><em>“The backend is blocking my request because of CORS.”</em></blockquote><p>That’s often an imprecise explanation.</p><p>More accurately:</p><blockquote><strong><em>The browser is refusing to expose the cross-origin response to the frontend because the server’s CORS policy doesn’t permit it.</em></strong></blockquote><h3>6. Why Postman Works While Browser Fails</h3><p>This is probably the most important practical section of the article.</p><p>Suppose:</p><pre>Frontend:<br>https://app.example.com<br><br>API:<br>https://api.example.com</pre><p>Your React application:</p><pre>fetch(&quot;https://api.example.com/users&quot;);</pre><p>produces:</p><pre>Access to fetch at<br>&#39;https://api.example.com/users&#39;<br>from origin<br>&#39;https://app.example.com&#39;<br>has been blocked by CORS policy</pre><p>You open Postman.</p><p>Same API:</p><pre>GET https://api.example.com/users</pre><p>Works perfectly.</p><p>Why?</p><p>Because <strong>Postman isn’t a browser page running JavaScript under the browser’s same-origin security model.</strong></p><p>So:</p><pre>Browser<br>   │<br>   │ CORS enforcement<br>   ▼<br>Server<br><br><br>Postman<br>   │<br>   │ HTTP request<br>   ▼<br>Server</pre><p>Postman can receive the HTTP response even when a browser would refuse to expose that response to page JavaScript. This distinction is also highlighted by Postman’s own explanation of CORS. (<a href="https://blog.postman.com/what-is-cors/?utm_source=chatgpt.com">Postman Blog</a>)</p><h3>7. Browser vs Postman vs Backend</h3><p>┌────────────────────────────────────┬───────────────┬───────────────┬──────────────────────┐<br>│ Feature │ Browser │ Postman │ Backend-to-Backend │<br>├────────────────────────────────────┼───────────────┼───────────────┼──────────────────────┤<br>│ Sends HTTP request │ ✅ Yes │ ✅ Yes │ ✅ Yes │<br>│ Same-Origin Policy │ ✅ Yes │ ❌ No │ ❌ No │<br>│ CORS enforcement │ ✅ Yes │ ❌ No │ ❌ No │<br>│ Sends Origin in browser CORS flow │ ✅ Yes │ ❌ No │ Depends │<br>│ Performs browser preflight │ ✅ Yes │ ❌ No │ ❌ No │<br>│ Blocks JS from reading response │ ✅ Yes │ ❌ No │ ❌ No │<br>│ Can call cross-origin APIs │ Subject to CORS│ Generally yes │ Yes │<br>│ Browser cookies/security context │ ✅ Yes │ Different │ Server-controlled │<br>│ Browser CORS error │ ✅ Yes │ ❌ No │ ❌ No │<br>└────────────────────────────────────┴───────────────┴───────────────┴──────────────────────┘</p><h3>The interview answer</h3><p>If an interviewer asks:</p><blockquote><strong><em>“Why does the API work in Postman but not in the browser?”</em></strong></blockquote><p>Don’t say:</p><blockquote><em>“Postman doesn’t support CORS.”</em></blockquote><p>A better answer is:</p><blockquote><strong><em>“CORS is a browser-enforced security mechanism. Postman is an HTTP client and isn’t subject to the browser’s same-origin enforcement, so the API can return a successful response in Postman while the browser refuses to expose that response to JavaScript.”</em></strong></blockquote><p>That’s the level of explanation expected from a senior engineer.</p><h3>8. Simple CORS Request</h3><p>Not every cross-origin request requires a preflight.</p><p>For example:</p><pre>fetch(&quot;https://api.example.com/users&quot;);</pre><p>The browser may send:</p><pre>GET /users HTTP/1.1<br>Host: api.example.com<br>Origin: https://app.example.com</pre><p>The server responds:</p><pre>HTTP/1.1 200 OK<br>Access-Control-Allow-Origin: https://app.example.com</pre><p>The browser sees that the origin is allowed and can expose the response to the JavaScript application. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>9. Preflight Request</h3><p>This is where many developers first encounter confusing CORS behavior.</p><p>Suppose we send:</p><pre>fetch(&quot;https://api.example.com/users&quot;, {<br>  method: &quot;POST&quot;,<br>  headers: {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    &quot;Authorization&quot;: &quot;Bearer token&quot;<br>  },<br>  body: JSON.stringify({<br>    name: &quot;Hareesh&quot;<br>  })<br>});</pre><p>The browser may first send:</p><pre>OPTIONS /users HTTP/1.1<br><br>Origin: https://app.example.com<br>Access-Control-Request-Method: POST<br>Access-Control-Request-Headers: authorization, content-type</pre><p>This is called a <strong>preflight request</strong>.</p><p>The server needs to indicate that the requested method and headers are permitted. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>10. Preflight Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C0L5qv5EDjJGCExx" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LMJ1FXtIAO3KNRS9" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*ZW1yHHdKEtmAroEj" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*Sge57K591m6Skp2a" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EqblgKGWUfPpwM_u" /></figure><pre>Browser<br>   │<br>   │ OPTIONS /users<br>   │ Origin: https://app.example.com<br>   │ Access-Control-Request-Method: POST<br>   │ Access-Control-Request-Headers:<br>   │ authorization, content-type<br>   ▼<br>API Server<br>   │<br>   │ 204 No Content<br>   │ Access-Control-Allow-Origin:<br>   │ https://app.example.com<br>   │ Access-Control-Allow-Methods: POST<br>   │ Access-Control-Allow-Headers:<br>   │ authorization, content-type<br>   ▼<br>Browser<br>   │<br>   │ Preflight approved<br>   ▼<br>Browser<br>   │<br>   │ POST /users<br>   │ Authorization: Bearer ...<br>   ▼<br>API Server<br>   │<br>   │ 200 OK<br>   ▼<br>Browser</pre><p>A preflight is automatically generated by the browser when the request qualifies for preflight; frontend developers normally don’t manually send it. (<a href="https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>11. When Does Preflight Happen?</h3><p>A request can require preflight because of things such as:</p><ul><li>certain HTTP methods</li><li>non-safelisted request headers</li><li>non-safelisted content types</li></ul><p>Common examples:</p><pre>PUT<br>PATCH<br>DELETE</pre><p>and:</p><pre>Authorization: Bearer ...</pre><p>or:</p><pre>Content-Type: application/json</pre><p>The exact CORS safelist rules matter, so don’t simplify this to:</p><blockquote><em>“POST always causes preflight.”</em></blockquote><p>That’s incorrect.</p><p>A POST can be a simple CORS request if it satisfies the safelist conditions. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>12. The Important CORS Headers</h3><p>┌───────────────────────────────────┬──────────┬────────────────────────────────────────────┐<br>│ Header │ Direction│ Purpose │<br>├───────────────────────────────────┼──────────┼────────────────────────────────────────────┤<br>│ Origin │ Request │ Identifies the requesting origin │<br>│ Access-Control-Allow-Origin │ Response │ Specifies the allowed origin │<br>│ Access-Control-Allow-Methods │ Response │ Specifies methods allowed for CORS │<br>│ Access-Control-Allow-Headers │ Response │ Specifies headers allowed │<br>│ Access-Control-Allow-Credentials │ Response │ Allows credentialed CORS requests │<br>│ Access-Control-Expose-Headers │ Response │ Exposes selected response headers │<br>│ Access-Control-Max-Age │ Response │ Controls preflight response caching │<br>└───────────────────────────────────┴──────────┴────────────────────────────────────────────┘</p><p>The Origin header is sent by the browser for CORS requests, and the server uses the CORS response headers to communicate the permitted access. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>13. Access-Control-Allow-Origin</h3><p>The simplest configuration:</p><pre>Access-Control-Allow-Origin: *</pre><p>means:</p><blockquote><em>Requests without credentials may be allowed from any origin.</em></blockquote><p>But:</p><pre>Access-Control-Allow-Origin: *</pre><p>cannot be combined with credentialed CORS requests. For credentialed requests, the server must return an explicit origin rather than *. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><p>For example:</p><pre>Access-Control-Allow-Origin: https://app.example.com</pre><h3>14. Why * Is Dangerous to Use Blindly</h3><p>This:</p><pre>Access-Control-Allow-Origin: *</pre><p>is convenient for public APIs.</p><p>But imagine:</p><pre>Application<br>    ↓<br>Private customer data<br>    ↓<br>Cookies / credentials</pre><p>You generally don’t want to make credentialed access available to arbitrary origins.</p><p>For authenticated applications, an allowlist is usually more appropriate:</p><pre>Allowed Origins:<br><br>https://app.company.com<br>https://admin.company.com<br>https://staging.company.com</pre><h3>15. Credentials and CORS</h3><p>This is another major interview topic.</p><p>Frontend:</p><pre>fetch(&quot;https://api.example.com/profile&quot;, {<br>  credentials: &quot;include&quot;<br>});</pre><p>Server:</p><pre>Access-Control-Allow-Origin: https://app.example.com<br>Access-Control-Allow-Credentials: true</pre><p>Notice:</p><pre>Access-Control-Allow-Origin: *</pre><p>is not valid for this credentialed CORS scenario. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>16. Cookies + CORS</h3><p>There are actually multiple concepts involved:</p><pre>CORS<br> +<br>Cookies<br> +<br>SameSite<br> +<br>Secure<br> +<br>credentials mode</pre><p>Simply adding:</p><pre>Access-Control-Allow-Credentials: true</pre><p>doesn’t magically make cookies work.</p><p>You also need to consider the cookie’s attributes and browser cookie policy.</p><p>This is why authentication-related CORS bugs can be much harder than basic API CORS problems.</p><h3>17. A Common Production Bug</h3><p>Frontend:</p><pre>axios.get(<br>  &quot;https://api.company.com/profile&quot;,<br>  {<br>    withCredentials: true<br>  }<br>);</pre><p>Backend:</p><pre>Access-Control-Allow-Origin: *<br>Access-Control-Allow-Credentials: true</pre><p>❌ This configuration is invalid for credentialed CORS.</p><p>Instead:</p><pre>Access-Control-Allow-Origin: https://app.company.com<br>Access-Control-Allow-Credentials: true</pre><p>The wildcard cannot be used with credentials. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>18. Access-Control-Allow-Headers</h3><p>Suppose frontend sends:</p><pre>Authorization: Bearer abc123<br>X-Client-Version: 2.4.1</pre><p>The preflight might contain:</p><pre>Access-Control-Request-Headers:<br>authorization, x-client-version</pre><p>The server needs to allow those headers:</p><pre>Access-Control-Allow-Headers:<br>Authorization, X-Client-Version</pre><p>Otherwise the browser can reject the CORS flow.</p><h3>19. Access-Control-Allow-Methods</h3><p>Suppose frontend wants:</p><pre>PATCH /users/123</pre><p>The preflight can ask:</p><pre>Access-Control-Request-Method: PATCH</pre><p>Server:</p><pre>Access-Control-Allow-Methods:<br>GET, POST, PUT, PATCH, DELETE, OPTIONS</pre><p>Now the browser knows that PATCH is allowed.</p><h3>20. OPTIONS Is Not the Actual API Request</h3><p>This is another common debugging mistake.</p><p>Developer sees:</p><pre>OPTIONS /users<br>204</pre><p>and thinks:</p><blockquote><em>“Why is my POST returning 204?”</em></blockquote><p>It may not be your POST at all.</p><p>It may be:</p><pre>OPTIONS → Preflight<br>POST     → Actual request</pre><p>In DevTools, look at the <strong>Method</strong> column carefully.</p><h3>21. What Happens When Preflight Fails?</h3><p>Suppose browser sends:</p><pre>OPTIONS /users</pre><p>Server responds:</p><pre>HTTP/1.1 204 No Content</pre><p>but doesn’t include:</p><pre>Access-Control-Allow-Origin</pre><p>or doesn’t allow the requested method/header.</p><p>The browser can stop the CORS flow and your JavaScript receives a CORS-related failure. CORS failures are intentionally not exposed to JavaScript with detailed security information; the browser console and network tools provide the useful diagnostics. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>22. CORS Debugging: My Production Workflow</h3><p>When someone tells me:</p><blockquote><strong><em>“API is working but frontend gets CORS error.”</em></strong></blockquote><p>I don’t immediately modify the frontend.</p><p>I follow this process:</p><pre>1. Check Browser Console<br>        ↓<br>2. Open Network Tab<br>        ↓<br>3. Find OPTIONS request<br>        ↓<br>4. Inspect Request Headers<br>        ↓<br>5. Inspect Response Headers<br>        ↓<br>6. Check Origin<br>        ↓<br>7. Check Allow-Origin<br>        ↓<br>8. Check Methods<br>        ↓<br>9. Check Headers<br>        ↓<br>10. Check Credentials<br>        ↓<br>11. Check Redirects<br>        ↓<br>12. Check Proxy / Gateway / CDN</pre><h3>23. The Browser DevTools Checklist</h3><p>For a failing request, inspect:</p><h3>Request</h3><pre>Origin: https://app.company.com</pre><p>If preflight exists:</p><pre>Access-Control-Request-Method: POST<br><br>Access-Control-Request-Headers:<br>authorization, content-type</pre><h3>Response</h3><p>Check:</p><pre>Access-Control-Allow-Origin<br>Access-Control-Allow-Methods<br>Access-Control-Allow-Headers<br>Access-Control-Allow-Credentials</pre><p>This tells you much more than simply looking at the red console error.</p><h3>24. Real-World Example: React + Node.js</h3><p>Frontend:</p><pre>const response = await fetch(<br>  &quot;https://api.example.com/users&quot;,<br>  {<br>    method: &quot;POST&quot;,<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      &quot;Authorization&quot;: `Bearer ${token}`<br>    },<br>    body: JSON.stringify(data)<br>  }<br>);</pre><p>Server:</p><pre>app.use(cors({<br>  origin: &quot;https://app.example.com&quot;,<br>  credentials: true<br>}));</pre><p>Conceptually, the server needs to respond appropriately to the browser’s CORS negotiation.</p><p>For a preflighted request, the browser may perform:</p><pre>OPTIONS<br>   ↓<br>CORS validation<br>   ↓<br>POST<br>   ↓<br>Response</pre><h3>25. Real-World Example: Multiple Environments</h3><p>Production:</p><pre>https://app.company.com</pre><p>Staging:</p><pre>https://staging.company.com</pre><p>Local:</p><pre>http://localhost:3000</pre><p>A common mistake is configuring:</p><pre>origin: &quot;https://app.company.com&quot;</pre><p>and then wondering why local development fails.</p><p>A better approach is an environment-specific allowlist.</p><pre>const allowedOrigins = [<br>  &quot;https://app.company.com&quot;,<br>  &quot;https://staging.company.com&quot;,<br>  &quot;http://localhost:3000&quot;<br>];</pre><p>The exact implementation depends on your backend framework and security requirements.</p><h3>26. CORS Behind API Gateway</h3><p>In larger systems:</p><pre>Browser<br>   │<br>   ▼<br>CDN<br>   │<br>   ▼<br>Load Balancer<br>   │<br>   ▼<br>API Gateway<br>   │<br>   ├── Service A<br>   ├── Service B<br>   └── Service C</pre><p>Now CORS might be configured at:</p><ul><li>CDN</li><li>load balancer</li><li>API gateway</li><li>application server</li></ul><p>This creates an important production debugging question:</p><blockquote><strong><em>Which layer is actually generating or modifying the CORS headers?</em></strong></blockquote><p>I’ve seen applications where the backend correctly returned:</p><pre>Access-Control-Allow-Origin</pre><p>but a gateway or proxy removed or replaced the header.</p><h3>27. CORS + Nginx</h3><p>A common architecture:</p><pre>Browser<br>   ↓<br>Nginx<br>   ↓<br>Node.js</pre><p>If Nginx handles OPTIONS differently from Node.js:</p><pre>GET     → Node.js<br>POST    → Node.js<br>OPTIONS → Nginx</pre><p>you can get a confusing situation where the actual endpoint works perfectly but preflight fails.</p><p>This is why I always check:</p><blockquote><strong><em>Who is answering the OPTIONS request?</em></strong></blockquote><h3>28. CORS + Redirects</h3><p>Preflighted requests combined with redirects can introduce additional browser compatibility/behavior issues.</p><p>For example:</p><pre>OPTIONS<br>   ↓<br>301 / 302<br>   ↓<br>https://another-api.example.com</pre><p>The browser may reject the flow depending on the circumstances and browser behavior. MDN specifically notes historical and implementation differences around redirects after preflight. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><p>A good production design is to avoid unnecessary redirects in API CORS flows.</p><h3>29. CORS Is NOT Authentication</h3><p>This distinction is extremely important.</p><p>CORS answers:</p><blockquote><strong><em>“Which browser origins are allowed to read this response?”</em></strong></blockquote><p>Authentication answers:</p><blockquote><strong><em>“Who is this user?”</em></strong></blockquote><p>Authorization answers:</p><blockquote><strong><em>“What is this user allowed to do?”</em></strong></blockquote><p>They are different concerns.</p><pre>Authentication<br>       ↓<br>Who are you?<br><br>Authorization<br>       ↓<br>What can you access?<br>CORS<br>       ↓<br>Can browser JavaScript from this origin<br>read the cross-origin response?<br></pre><p>Never treat CORS as your authentication mechanism.</p><h3>30. CORS Is NOT CSRF Protection</h3><p>Another common interview trap.</p><p>CORS and CSRF are related to browser security but solve different problems.</p><p>CORSCSRFControls cross-origin access to responsesProtects against unwanted state-changing requestsBrowser enforcementApplication/server defenseUses CORS headersOften uses CSRF tokens and cookie policiesConcerned with response sharingConcerned with unauthorized actions</p><p>The same-origin policy and cross-origin request behavior have separate implications for reads, writes and embeddings. (<a href="https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Same-origin_policy?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>31. CORS vs CSRF vs Same-Origin Policy</h3><pre>                 Browser Security<br>                       │<br>          ┌────────────┼────────────┐<br>          │            │            │<br>          ▼            ▼            ▼<br>         SOP          CORS         CSRF<br>          │            │            │<br>      Default       Controlled     Prevent<br>      boundary      sharing        unwanted<br>                                   actions</pre><p>A senior engineer should know the difference.</p><h3>32. CORS vs CORP vs COEP</h3><p>As applications become more security-sensitive, you may encounter:</p><pre>CORS<br>CORP<br>COEP<br>COOP</pre><p>They are <strong>not interchangeable</strong>.</p><h3>CORS</h3><p>Controls whether cross-origin responses can be shared with browser JavaScript.</p><h3>CORP</h3><p>Cross-Origin-Resource-Policy controls whether resources can be loaded cross-origin under the relevant browser request mode. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cross-Origin_Resource_Policy?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>COEP</h3><p>Cross-Origin-Embedder-Policy controls embedding requirements for resources.</p><h3>COOP</h3><p>Cross-Origin-Opener-Policy controls relationships between browsing contexts/windows.</p><p>For most frontend API debugging, start with:</p><pre>SOP → CORS</pre><p>and then understand CORP/COEP/COOP when your application’s security or isolation requirements need them.</p><h3>33. CORS and Vary: Origin</h3><p>Suppose your server dynamically returns:</p><pre>Access-Control-Allow-Origin: https://app.company.com</pre><p>or:</p><pre>Access-Control-Allow-Origin: https://admin.company.com</pre><p>depending on the incoming Origin.</p><p>In such cases, caching needs to account for the request origin.</p><p>A response that varies based on Origin should include:</p><pre>Vary: Origin</pre><p>so caches understand that responses can differ by origin. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Origin?utm_source=chatgpt.com">MDN Web Docs</a>)</p><p>This is a detail many developers miss until CORS behaves strangely behind a CDN.</p><h3>34. The Dangerous CORS Configuration</h3><p>Avoid blindly doing:</p><pre>Access-Control-Allow-Origin: *</pre><p>with:</p><pre>Access-Control-Allow-Credentials: true</pre><p>Also avoid reflecting arbitrary origins without validation:</p><pre>res.setHeader(<br>  &quot;Access-Control-Allow-Origin&quot;,<br>  req.headers.origin<br>);</pre><p>without an allowlist.</p><p>Instead:</p><pre>const allowedOrigins = [<br>  &quot;https://app.company.com&quot;,<br>  &quot;https://admin.company.com&quot;<br>];<br><br>if (allowedOrigins.includes(req.headers.origin)) {<br>  res.setHeader(<br>    &quot;Access-Control-Allow-Origin&quot;,<br>    req.headers.origin<br>  );<br>}</pre><p>Then consider the required credentials, methods, headers and caching behavior.</p><h3>35. Common CORS Mistakes</h3><p>┌────────────────────────────────────┬──────────────────────────────────────────────────────────────┐<br>│ Mistake │ Why It’s Wrong │<br>├────────────────────────────────────┼──────────────────────────────────────────────────────────────┤<br>│ “Disable CORS in React” │ CORS is primarily a server/browser interaction │<br>│ “It works in Postman, so API is │ Postman isn’t subject to browser CORS enforcement │<br>│ fine” │ │<br>│ `Allow-Origin: *` with credentials│ Invalid credentialed CORS configuration │<br>│ Ignore `OPTIONS` │ Preflight can fail before the actual request │<br>│ Assume every POST preflights │ Simple POST requests can avoid preflight │<br>│ Add random headers │ Non-safelisted headers can trigger preflight │<br>│ Treat CORS as authentication │ CORS and authentication solve different security concerns │<br>│ Treat CORS as CSRF protection │ CORS and CSRF address different attack models │<br>│ Only inspect the console │ Network tab provides critical request/response details │<br>│ Configure only the backend │ Gateway/CDN/proxy may modify CORS behavior │<br>│ Forget `Vary: Origin` │ Can create caching issues for dynamic origins │<br>└────────────────────────────────────┴──────────────────────────────────────────────────────────────┘</p><h3>36. CORS Debugging Decision Tree</h3><pre>                  CORS ERROR<br>                     │<br>                     ▼<br>             Check Network Tab<br>                     │<br>              ┌──────┴──────┐<br>              │             │<br>         OPTIONS exists?    No<br>              │             │<br>             YES            ▼<br>              │        Inspect actual<br>              ▼          response<br>       Check OPTIONS<br>       response headers<br>              │<br>       ┌──────┴──────┐<br>       │             │<br>      FAIL          PASS<br>       │             │<br>       ▼             ▼<br> Fix preflight    Check actual<br>                  response CORS<br>                       │<br>                       ▼<br>                Check credentials<br>                       │<br>                       ▼<br>                 Check cookies<br>                       │<br>                       ▼<br>                Check proxy/CDN</pre><h3>37. Browser vs Postman: The Mental Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*aXHs0F66_kS2LyB-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*60pM-gQYVR8hsykH" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DD8thGg6pmdETx6D" /></figure><p>Think about it this way:</p><pre>                   API SERVER<br>                        │<br>             ┌──────────┴──────────┐<br>             │                     │<br>             │                     │<br>         Browser                Postman<br>             │                     │<br>       Same-Origin             HTTP Client<br>       Policy + CORS              │<br>             │                     │<br>       CORS validation             │<br>             │                     │<br>        ┌────┴────┐                │<br>        │         │                │<br>      Allow      Block             │<br>        │         │                │<br>        ▼         ▼                ▼<br>       JS      CORS Error        Response<br>     Response</pre><p>This single diagram explains a huge percentage of CORS confusion.</p><h3>38. Real Interview Scenario #1</h3><h3>Interviewer:</h3><blockquote><em>“The API returns 200 in Postman but gives CORS error in React. What do you check?”</em></blockquote><h3>Strong answer:</h3><blockquote><em>“First I’d confirm whether this is actually a CORS issue by checking the browser console and Network tab. I’d inspect the request’s </em><em>Origin, determine whether there is an </em><em>OPTIONS preflight, and inspect the response headers for </em><em>Access-Control-Allow-Origin, methods, headers and credentials. I&#39;d also check whether a proxy, API gateway or CDN is handling the request. Postman succeeding doesn&#39;t disprove a CORS problem because Postman isn&#39;t subject to browser CORS enforcement.&quot;</em></blockquote><p>That’s a much stronger answer than:</p><blockquote><em>“I’ll add </em><em>Access-Control-Allow-Origin: *.&quot;</em></blockquote><h3>39. Real Interview Scenario #2</h3><h3>Interviewer:</h3><blockquote><em>“Why does GET work but DELETE fail?”</em></blockquote><p>Possible explanation:</p><pre>GET<br> ↓<br>Simple CORS request<br> ↓<br>Server response</pre><p>while:</p><pre>DELETE<br> ↓<br>Preflight<br> ↓<br>OPTIONS<br> ↓<br>Server must allow DELETE<br> ↓<br>DELETE</pre><p>If the server doesn’t properly handle the preflight, DELETE may never be sent.</p><h3>40. Real Interview Scenario #3</h3><h3>Interviewer:</h3><blockquote><em>“Why does the API work locally but fail in production?”</em></blockquote><p>Possible causes:</p><pre>localhost origin<br>        ≠<br>production origin</pre><p>or:</p><ul><li>production allowlist missing</li><li>CDN behavior</li><li>API gateway</li><li>HTTPS/HTTP differences</li><li>redirect</li><li>credentials configuration</li><li>proxy configuration</li><li>different API domain</li><li>different cookie configuration</li></ul><p>Don’t assume:</p><blockquote><em>“The code changed.”</em></blockquote><p>Sometimes the environment changed.</p><h3>41. Real Interview Scenario #4</h3><h3>Interviewer:</h3><blockquote><em>“Can you fix CORS from React?”</em></blockquote><p>My answer:</p><blockquote><strong><em>“Usually the real fix belongs on the server or infrastructure layer because the server controls the CORS response headers. On the frontend I can change the request shape, credentials mode or development proxy when appropriate, but I can’t make a production browser accept an invalid server CORS policy just by adding a frontend header.”</em></strong></blockquote><p>MDN similarly notes that most CORS errors are resolved on the server side. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS/Errors?utm_source=chatgpt.com">MDN Web Docs</a>)</p><h3>42. Development Proxy</h3><p>During local development, you might have:</p><pre>Browser<br>   │<br>   ▼<br>http://localhost:3000<br>   │<br>   │ proxy<br>   ▼<br>https://api.company.com</pre><p>The browser may perceive the frontend request as same-origin with the development server while the dev server proxies it to the API.</p><p>This can make local development easier.</p><p>But remember:</p><blockquote><strong><em>A development proxy doesn’t automatically fix the production CORS configuration.</em></strong></blockquote><h3>43. Production Architecture</h3><p>A mature application might look like:</p><pre>                   Internet<br>                       │<br>                       ▼<br>                      CDN<br>                       │<br>                       ▼<br>                 Load Balancer<br>                       │<br>                       ▼<br>                  API Gateway<br>                       │<br>          ┌────────────┼────────────┐<br>          ▼            ▼            ▼<br>       Auth API     User API     Order API<br>          │            │            │<br>          └────────────┼────────────┘<br>                       ▼<br>                    Database</pre><p>CORS needs to be considered across the actual request path.</p><p>The question isn’t merely:</p><blockquote><em>“Did Node.js add CORS?”</em></blockquote><p>The better question is:</p><blockquote><strong><em>“What response reaches the browser, and which infrastructure layer generated it?”</em></strong></blockquote><h3>44. My 10+ Year CORS Debugging Checklist</h3><p>When I see a CORS issue, I check:</p><pre>□ Origin<br>□ Scheme<br>□ Host<br>□ Port<br>□ Request method<br>□ Request headers<br>□ Content-Type<br>□ OPTIONS request<br>□ OPTIONS status<br>□ Allow-Origin<br>□ Allow-Methods<br>□ Allow-Headers<br>□ Allow-Credentials<br>□ Credentials mode<br>□ Cookies<br>□ SameSite<br>□ Redirects<br>□ API Gateway<br>□ Nginx<br>□ CDN<br>□ Cache<br>□ Vary: Origin<br>□ Environment configuration</pre><p>This prevents random trial-and-error changes.</p><h3>45. CORS Interview Cheat Sheet</h3><p>┌───────────────────────────────┬──────────────────────────────────────────────────────────────────────┐<br>│ Question │ Senior-Level Answer │<br>├───────────────────────────────┼──────────────────────────────────────────────────────────────────────┤<br>│ What is CORS? │ Browser-enforced cross-origin response sharing controlled through │<br>│ │ HTTP headers. │<br>│ Why does Postman work? │ It isn’t subject to browser Same-Origin Policy/CORS enforcement. │<br>│ What is SOP? │ Browser security boundary based on scheme, host, and port. │<br>│ What is preflight? │ Browser-generated OPTIONS request used to check whether a │<br>│ │ cross-origin request is permitted. │<br>│ Does every POST preflight? │ No. Some simple POST requests can avoid preflight. │<br>│ Why does DELETE often │ DELETE is not a CORS-safelisted method, so it commonly triggers │<br>│ preflight? │ a preflight request. │<br>│ What does Origin mean? │ Identifies the origin making the cross-origin request. │<br>│ What does Allow-Origin mean? │ Specifies which origin the browser may allow to access the response.│<br>│ Why can’t * be used with │ Credentialed CORS requires an explicit allowed origin. │<br>│ credentials? │ │<br>│ What is Allow-Headers? │ Specifies which request headers are permitted for the CORS request.│<br>│ What is Allow-Methods? │ Specifies which HTTP methods are permitted for the CORS request. │<br>│ Who enforces CORS? │ The browser. │<br>│ Can Postman have a CORS │ Not in the browser-CORS sense. │<br>│ error? │ │<br>│ Can frontend code fix server │ Not directly. The server/infrastructure must provide the correct │<br>│ CORS? │ CORS response behavior. │<br>│ Is CORS authentication? │ No. Authentication determines who the user/client is. │<br>│ Is CORS CSRF protection? │ No. CORS and CSRF address different security concerns. │<br>│ Why check OPTIONS? │ It may be the failing preflight request that prevents the actual │<br>│ │ request from being sent. │<br>│ Why Vary: Origin? │ Cached responses can differ based on the requesting Origin. │<br>│ Can CDN cause CORS issues? │ Yes. CDN caching or header manipulation can affect CORS behavior. │<br>│ Can Nginx cause CORS issues? │ Yes. Nginx can handle OPTIONS or modify response headers. │<br>│ Can API Gateway cause CORS │ Yes. API gateways can add, remove, or modify CORS headers. │<br>│ issues? │ │<br>└───────────────────────────────┴──────────────────────────────────────────────────────────────────────┘</p><h3>46. Final Mental Model</h3><p>If you remember only one thing from this article, remember this:</p><pre>                     SAME ORIGIN?<br>                         │<br>                ┌────────┴────────┐<br>                │                 │<br>               YES                NO<br>                │                 │<br>                ▼                 ▼<br>           Normal flow       Browser CORS rules<br>                                  │<br>                           ┌──────┴──────┐<br>                           │             │<br>                      Simple request   Preflight<br>                           │             │<br>                           │          OPTIONS<br>                           │             │<br>                           │        Server approval<br>                           │             │<br>                           └──────┬──────┘<br>                                  │<br>                                  ▼<br>                              Actual API<br>                                  │<br>                                  ▼<br>                         CORS response check<br>                                  │<br>                           ┌──────┴──────┐<br>                           │             │<br>                         Allow         Block<br>                           │             │<br>                           ▼             ▼<br>                         Data       CORS Error</pre><p>And the second thing:</p><pre>&quot;Works in Postman&quot;<br>                      ≠<br>             &quot;Works in Browser&quot;</pre><p>Because:</p><pre>Postman<br>   ↓<br>HTTP client<br>   ↓<br>API<br><br>Browser<br>   ↓<br>HTTP request<br>   ↓<br>Same-Origin Policy<br>   ↓<br>CORS validation<br>   ↓<br>JavaScript access</pre><h3>47. Final Takeaway</h3><p>After 10+ years of frontend development, I don’t consider CORS just another HTTP-header topic.</p><p>It sits at the intersection of:</p><pre>Browser Security<br>       +<br>HTTP<br>       +<br>Frontend<br>       +<br>Backend<br>       +<br>Authentication<br>       +<br>Cookies<br>       +<br>API Gateway<br>       +<br>CDN<br>       +<br>Infrastructure</pre><p>And that’s why CORS issues can be deceptively difficult.</p><p>The most important shift in thinking is:</p><blockquote><strong><em>Don’t ask “How do I remove the CORS error?”</em></strong></blockquote><p>Ask:</p><blockquote><strong><em>“What origin is making the request, what request is the browser actually sending, is there a preflight, what response headers are coming back, and which layer is responsible for them?”</em></strong></blockquote><p>Once you think that way, CORS stops being mysterious.</p><h3>🎯 Interview Questions to Practice</h3><p>For a <strong>10+ year Frontend / Lead Frontend Developer</strong>, I would prepare these beyond the basic definitions:</p><h3>Fundamentals</h3><ol><li>What is CORS?</li><li>What is Same-Origin Policy?</li><li>What exactly defines an origin?</li><li>Why is https://example.com different from <a href="http://example.com/?">http://example.com?</a></li><li>Is https://api.example.com same-origin with <a href="https://example.com/?">https://example.com?</a></li></ol><h3>Browser vs API Clients</h3><ol><li>Why does Postman work when browser fails?</li><li>Does Postman support CORS?</li><li>Does Axios cause CORS?</li><li>Does fetch() cause CORS?</li><li>Can a backend-to-backend request have a browser CORS error?</li></ol><h3>Preflight</h3><ol><li>What is a preflight request?</li><li>Why does the browser send OPTIONS?</li><li>Does every POST trigger preflight?</li><li>Why might DELETE trigger preflight?</li><li>What headers appear in a preflight?</li><li>What happens if OPTIONS returns 404?</li><li>What happens if OPTIONS returns 200 but lacks CORS headers?</li><li>Can preflight be cached?</li></ol><h3>Credentials</h3><ol><li>How does credentials: &quot;include&quot; affect CORS?</li><li>Why can’t wildcard origin be used with credentials?</li><li>How do cookies interact with CORS?</li><li>What is SameSite?</li><li>Why can CORS work but cookies still fail?</li></ol><h3>Production</h3><ol><li>How would you debug CORS behind Nginx?</li><li>How would you debug CORS behind an API Gateway?</li><li>How could a CDN break CORS?</li><li>Why is Vary: Origin important?</li><li>How would you configure multiple environments?</li><li>How would you handle dynamic allowed origins securely?</li><li>What happens when an API redirects during a CORS flow?</li></ol><h3>Architecture</h3><ol><li>CORS vs CSRF?</li><li>CORS vs CORP?</li><li>CORS vs COEP?</li><li>CORS vs COOP?</li><li>Is CORS a security mechanism?</li><li>Is CORS authentication?</li><li>Can CORS protect an API from Postman/cURL?</li><li>Can CORS prevent server-to-server requests?</li></ol><h3>Lead-Level Scenarios</h3><ol><li><strong>“Works in Postman, fails in React. Debug it.”</strong></li><li><strong>“GET works, POST fails. Why?”</strong></li><li><strong>“GET works, DELETE fails. Why?”</strong></li><li><strong>“Local works, production fails. What do you investigate?”</strong></li><li><strong>“OPTIONS returns 204 but POST never happens. Why?”</strong></li><li><strong>“CORS headers exist on Node.js but browser still fails. What could be happening?”</strong></li><li><strong>“CORS works until we introduce CloudFront/CDN/API Gateway. What do you check?”</strong></li><li><strong>“How would you design CORS for a multi-tenant SaaS application?”</strong></li><li><strong>“How would you safely allow 50 customer domains?”</strong></li><li><strong>“Would you use </strong><strong>Access-Control-Allow-Origin: * for an authenticated application? Why?&quot;</strong></li></ol><p>These questions are where the difference between <strong>knowing CORS terminology</strong> and actually having <strong>production-level frontend experience</strong> becomes visible.</p><h3>References</h3><p>For the standards-level details, the best reference is <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN — Cross-Origin Resource Sharing (CORS)</a>, especially its coverage of simple requests, preflight, credentials and CORS headers. (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS?utm_source=chatgpt.com">MDN Web Docs</a>)</p><p>Also useful: <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Same-origin_policy?utm_source=chatgpt.com">MDN — Same-Origin Policy</a> for understanding why CORS exists in the first place. (<a href="https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Same-origin_policy?utm_source=chatgpt.com">MDN Web Docs</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f14d0b7b08d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend Performance Engineering: A 10+ Year Journey Through React Fiber, Webpack, Vite, Lighthouse…]]></title>
            <link>https://medium.com/@hareeshdwivedi.vns.9198/frontend-performance-engineering-a-10-year-journey-through-react-fiber-webpack-vite-lighthouse-73db8bc5322e?source=rss-86083c5393c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/73db8bc5322e</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <dc:creator><![CDATA[Hareesh Dwivedi ]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 16:51:21 GMT</pubDate>
            <atom:updated>2026-08-19T16:51:21.719Z</atom:updated>
            <content:encoded><![CDATA[<h4>Frontend Performance Engineering: A 10+ Year Journey Through React Fiber, Webpack, Vite, Lighthouse &amp; Core Web Vitals</h4><p>A practical guide to diagnosing, optimizing and monitoring real-world React applications — with production examples and senior-level interview questions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x7pKHBm7dKFMSHFI" /></figure><blockquote><strong><em>The fastest application isn’t necessarily the one with the smallest bundle. It’s the one that makes the least unnecessary work.</em></strong></blockquote><p>After 10+ years of frontend development, I’ve worked on applications ranging from traditional web applications to React-based SPAs, dashboards, SaaS platforms, data-heavy interfaces and applications where responsiveness is critical.</p><p>One thing I’ve learned repeatedly is that frontend performance is rarely caused by a single problem.</p><p>A slow application might have:</p><ul><li>excessive JavaScript</li><li>inefficient React rendering</li><li>large DOM trees</li><li>unnecessary Redux updates</li><li>API waterfalls</li><li>oversized images</li><li>expensive computations</li><li>memory leaks</li><li>poor caching</li><li>third-party scripts</li><li>slow server responses</li><li>hydration overhead</li><li>or several of these problems at the same time.</li></ul><p>That’s why I don’t start performance optimization by asking:</p><blockquote><strong><em>“Which optimization technique should I use?”</em></strong></blockquote><p>I start with:</p><blockquote><strong><em>“Where is the user actually spending time?”</em></strong></blockquote><h3>1. What Does Frontend Performance Actually Mean?</h3><p>Frontend performance isn’t just page load time.</p><p>A modern application has several performance dimensions.</p><pre>User<br> │<br> ▼<br>Navigation<br> │<br> ▼<br>DNS / Connection<br> │<br> ▼<br>Server Response<br> │<br> ▼<br>HTML<br> │<br> ├── CSS<br> ├── JavaScript<br> └── Images<br>       │<br>       ▼<br>   Browser Processing<br>       │<br>       ▼<br>      React<br>       │<br>       ▼<br>  DOM Updates<br>       │<br>       ▼<br> Layout / Paint<br>       │<br>       ▼<br>    Screen<br>       │<br>       ▼<br> User Interaction<br>       │<br>       ▼<br>      INP</pre><p>So when someone says:</p><blockquote><em>“The application is slow.”</em></blockquote><p>I want to know <strong>which part is slow</strong>.</p><p>┌──────────────────────────────┬──────────────────────────────┐<br>│ Symptom │ Possible cause │<br>├──────────────────────────────┼──────────────────────────────┤<br>│ Content appears late │ LCP / TTFB / assets │<br>│ Page freezes │ Long JavaScript task │<br>│ Button feels slow │ INP / event handler │<br>│ Scrolling is janky │ JS / layout / paint │<br>│ Content jumps │ CLS │<br>│ Initial bundle is huge │ Dependencies / bundling │<br>│ Dashboard slows down │ Rendering / DOM / memory │<br>│ Navigation is slow │ API / chunks / rendering │<br>│ First visit is slow │ Network / caching │<br>│ Mobile is slow │ CPU / network / JS │<br>└──────────────────────────────┴───────────────</p><h3>Interview Follow-up Questions</h3><p><strong>Q: What are the major dimensions of frontend performance?</strong></p><p>A strong answer should mention:</p><ul><li>loading performance</li><li>rendering performance</li><li>runtime performance</li><li>interaction responsiveness</li><li>network performance</li><li>memory usage</li><li>visual stability</li><li>real-user performance</li></ul><p><strong>Q: If a user says “the page is slow”, what do you do first?</strong></p><p>I wouldn’t immediately optimize code.</p><p>I’d reproduce the problem and establish a baseline using:</p><ul><li>Chrome DevTools</li><li>Network tab</li><li>Performance panel</li><li>Lighthouse</li><li>React Profiler</li><li>Memory profiler</li><li>bundle analysis</li><li>production/RUM data</li></ul><p>Then I’d identify the bottleneck before changing anything.</p><h3>2. Start With Measurement, Not Optimization</h3><p>One of the biggest mistakes in performance work is optimizing without establishing a baseline.</p><p>For example:</p><h3>Before</h3><pre>LCP              4.2s<br>INP              380ms<br>CLS              0.24<br><br>JS downloaded    1.7MB<br>DOM nodes        12,400<br>API requests     53<br>Largest chunk    780KB</pre><p>After optimization:</p><pre>LCP              2.1s<br>INP              145ms<br>CLS              0.04<br><br>JS downloaded    680KB<br>DOM nodes        3,400<br>API requests     24<br>Largest chunk    240KB</pre><p>Now we can demonstrate whether the optimization actually worked.</p><p>My general process is:</p><pre>Reproduce<br>   ↓<br>Measure<br>   ↓<br>Profile<br>   ↓<br>Identify bottleneck<br>   ↓<br>Form hypothesis<br>   ↓<br>Optimize<br>   ↓<br>Measure again<br>   ↓<br>Regression test<br>   ↓<br>Monitor production</pre><h3>Interview Follow-up Questions</h3><p><strong>Q: What tools do you use for frontend performance debugging?</strong></p><p>I’d typically use:</p><ul><li>Chrome DevTools Network</li><li>Chrome Performance</li><li>Chrome Memory</li><li>Lighthouse</li><li>React DevTools Profiler</li><li>Webpack Bundle Analyzer</li><li>Vite/Rollup analysis</li><li>WebPageTest</li><li>Core Web Vitals</li><li>RUM/observability tools</li></ul><p><strong>Q: Why shouldn’t we optimize based only on Lighthouse?</strong></p><p>Because Lighthouse is a controlled lab environment.</p><p>Real users have different:</p><ul><li>devices</li><li>CPUs</li><li>networks</li><li>browsers</li><li>locations</li><li>interaction patterns</li></ul><p>So I use <strong>lab data + real-user data</strong>.</p><h3>3. Understanding the Browser Rendering Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*xONTeN7frNgLG8d5" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_7AqGHMbQKa21E9F" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/0*XFOjEajUPNI7d78-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*hfRbGF4T9zXeSTh2" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*oGFI12-JeeykCAqs" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QNQnkyLmx3uoi5ou" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pK71PrP4AETXYW8D" /></figure><p>A simplified rendering pipeline looks like:</p><pre>HTML<br> │<br> ▼<br>DOM<br> │<br>CSS<br> │<br> ▼<br>CSSOM<br> │<br> ▼<br>Render Tree<br> │<br> ▼<br>Layout<br> │<br> ▼<br>Paint<br> │<br> ▼<br>Composite<br> │<br> ▼<br>Screen</pre><p>Each stage can become a bottleneck.</p><p>For example, JavaScript can trigger:</p><ul><li>style recalculation</li><li>layout</li><li>paint</li><li>compositing</li></ul><p>A senior frontend engineer should understand not just React, but what the browser does <strong>after React finishes rendering</strong>.</p><h3>Real Example</h3><p>Suppose we repeatedly do:</p><pre>element.style.width = &#39;500px&#39;;<br>const height =<br>  element.getBoundingClientRect().height;<br>element.style.height = `${height}px`;</pre><p>Repeated read/write operations can cause the browser to perform layout work more frequently than necessary.</p><p>A better approach is often to batch operations:</p><pre>READ<br>READ<br>READ<br><br>WRITE<br>WRITE<br>WRITE</pre><p>instead of:</p><pre>READ<br>WRITE<br>READ<br>WRITE<br>READ<br>WRITE</pre><h3>Interview Follow-up Questions</h3><p><strong>Q: What is layout thrashing?</strong></p><p>Repeatedly forcing the browser to calculate layout between DOM reads and writes.</p><p><strong>Q: Difference between layout, paint and composite?</strong></p><ul><li><strong>Layout:</strong> determines geometry.</li><li><strong>Paint:</strong> draws visual elements.</li><li><strong>Composite:</strong> combines rendered layers.</li></ul><p><strong>Q: Why can </strong><strong>transform and </strong><strong>opacity be preferable for animations?</strong></p><p>They can often be handled more efficiently by compositing without requiring full layout recalculation.</p><h3>4. JavaScript Runtime and the Main Thread</h3><p>JavaScript execution happens primarily on the browser’s main thread.</p><p>That thread also has to deal with:</p><ul><li>DOM work</li><li>style calculation</li><li>layout</li><li>paint coordination</li><li>event handling</li></ul><p>So if we execute a large synchronous task:</p><pre>processHugeDataset();</pre><p>the browser may not get an opportunity to respond to the user.</p><pre>User clicks<br>     │<br>     ▼<br>500ms JavaScript<br>     │<br>     ▼<br>Browser finally paints</pre><p>The user experiences:</p><blockquote><em>“The application froze.”</em></blockquote><h3>Long Tasks</h3><p>A long task is essentially a task that occupies the main thread for too long.</p><p>Typical causes include:</p><ul><li>large data processing</li><li>expensive loops</li><li>JSON transformation</li><li>large synchronous calculations</li><li>excessive React rendering</li><li>third-party scripts</li></ul><h3>Interview Follow-up Questions</h3><p><strong>Q: What is the JavaScript event loop?</strong></p><p>You should be able to explain:</p><pre>Call Stack<br>    ↓<br>Web APIs<br>    ↓<br>Task Queue / Microtask Queue<br>    ↓<br>Event Loop<br>    ↓<br>Call Stack</pre><p><strong>Q: Microtask vs macrotask?</strong></p><p>Examples:</p><p>Microtasks:</p><ul><li>Promise callbacks</li><li>queueMicrotask</li><li>MutationObserver</li></ul><p>Tasks/macrotasks:</p><ul><li>timers</li><li>DOM events</li><li>network callbacks</li></ul><p><strong>Q: Why can too many microtasks also hurt performance?</strong></p><p>Because the browser generally needs to drain microtasks before moving on, potentially delaying rendering and user interaction.</p><h3>5. React Fiber</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i31KN2Ek-4JeDYe6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*0H8kZMlbGY0SaRGw" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*dNuvFcoIQTJyjASI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*M5zqOk1bJPNStmoF" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/0*YmMWCWCYp4s6A_uW" /></figure><p>React Fiber is one of the most important concepts for understanding modern React rendering.</p><p>A simplified model:</p><pre>State Update<br>     │<br>     ▼<br>Schedule Work<br>     │<br>     ▼<br>Fiber Tree<br>     │<br>     ▼<br>Render Phase<br>     │<br>     ▼<br>Reconciliation<br>     │<br>     ▼<br>Commit Phase<br>     │<br>     ▼<br>    DOM</pre><p>The important distinction is between:</p><h3>Render phase</h3><p>React determines what the UI should look like.</p><h3>Commit phase</h3><p>React applies the required changes to the DOM.</p><p>Fiber allows React to represent rendering work as units that can be scheduled and prioritized.</p><h3>Real Example</h3><p>Imagine a dashboard:</p><pre>Dashboard<br> ├── Header<br> ├── Filters<br> ├── Revenue Chart<br> ├── Sales Chart<br> ├── Orders Table<br> └── Notifications</pre><p>A filter update happens.</p><p>If the entire tree unnecessarily re-renders:</p><pre>Filter<br> ↓<br>Dashboard<br> ↓<br>Chart<br> ↓<br>Chart<br> ↓<br>Table<br> ↓<br>Notifications</pre><p>we need to investigate why.</p><p>The answer isn’t automatically:</p><pre>React.memo(...)</pre><p>The real problem could be:</p><ul><li>state located too high</li><li>unstable props</li><li>context updates</li><li>broad Redux subscriptions</li><li>expensive calculations</li></ul><h3>Interview Follow-up Questions</h3><p><strong>Q: What is React Fiber?</strong></p><p>Fiber is React’s internal architecture for representing and scheduling rendering work.</p><p><strong>Q: What is reconciliation?</strong></p><p>The process through which React determines what needs to change between renders.</p><p><strong>Q: Render phase vs commit phase?</strong></p><p>Render determines what should change; commit applies the changes.</p><p><strong>Q: Can React interrupt work?</strong></p><p>Modern React’s scheduling architecture allows certain rendering work to be interrupted or prioritized.</p><h3>6. React Re-rendering and Memoization</h3><p>One of the most common mistakes I’ve seen is:</p><blockquote><em>“The component is slow, let’s add </em><em>useMemo.&quot;</em></blockquote><p>That’s not necessarily the right diagnosis.</p><p>I first ask:</p><pre>Why is it rendering?</pre><p>Possible reasons:</p><ul><li>local state changed</li><li>parent rendered</li><li>props changed</li><li>context changed</li><li>Redux selector changed</li><li>expensive calculation</li><li>unstable references</li></ul><h3>React.memo</h3><p>Useful when a component receives stable props and unnecessary parent-driven renders are expensive.</p><pre>const UserCard = React.memo(<br>  function UserCard({ user }) {<br>    return &lt;div&gt;{user.name}&lt;/div&gt;;<br>  }<br>);</pre><p>But if:</p><pre>&lt;UserCard<br>  user={{ ...user }}<br>/&gt;</pre><p>creates a new object every render, memoization may not provide the expected benefit.</p><h3>useMemo</h3><p>Useful when a calculation is genuinely expensive:</p><pre>const filtered = useMemo(() =&gt; {<br>  return expensiveFilter(users, search);<br>}, [users, search]);</pre><p>But don’t use it everywhere.</p><h3>useCallback</h3><p>Useful when function identity matters, particularly when passing callbacks to memoized children.</p><p>It isn’t a magic performance switch.</p><h3>Interview Follow-up Questions</h3><p><strong>Q: When would you use </strong><strong>useMemo?</strong></p><p>When profiling shows an expensive calculation that can benefit from memoization.</p><p><strong>Q: </strong><strong>useMemo vs </strong><strong>useCallback?</strong></p><p>useMemo caches a value.</p><p>useCallback caches a function reference.</p><p><strong>Q: Can excessive memoization hurt performance?</strong></p><p>Yes. It adds complexity and dependency tracking, and the comparison/memoization overhead may not be worthwhile for cheap work.</p><h3>7. useTransition and useDeferredValue</h3><p>For large interfaces, not all updates have equal priority.</p><p>For example:</p><pre>Typing in search box<br>       │<br>       ├── immediate<br>       │<br>       ▼<br>Update expensive result list<br>       │<br>       └── lower priority</pre><p>React provides mechanisms such as:</p><pre>startTransition(() =&gt; {<br>  setSearch(value);<br>});</pre><p>The objective isn’t to make the computation disappear.</p><p>It is to keep urgent interactions responsive while expensive UI work is treated differently.</p><h3>Interview Follow-up Questions</h3><p><strong>Q: What problem does </strong><strong>useTransition solve?</strong></p><p>It allows certain state updates to be treated as non-urgent so urgent UI interactions can remain responsive.</p><p><strong>Q: Does </strong><strong>useTransition make expensive code faster?</strong></p><p>No.</p><p>It changes scheduling/priority; it doesn’t magically reduce the computational cost.</p><p><strong>Q: </strong><strong>useTransition vs </strong><strong>useDeferredValue?</strong></p><p>useTransition is useful when you control the state update.</p><p>useDeferredValue is useful when you want to consume a value at a lower priority.</p><h3>8. Redux Performance</h3><p>Redux can become a performance problem when components subscribe too broadly.</p><p>Avoid unnecessarily broad subscriptions such as:</p><pre>const state = useSelector(<br>  state =&gt; state<br>);</pre><p>Prefer focused selectors:</p><pre>const user = useSelector(<br>  selectCurrentUser<br>);<br><br>const orders = useSelector(<br>  selectOrders<br>);</pre><p>For derived data, memoized selectors can help prevent unnecessary recalculation.</p><h3>Real Example</h3><p>Suppose a dashboard has:</p><pre>User<br>Orders<br>Charts<br>Notifications<br>Activity</pre><p>A filter changes.</p><p>If the filter causes all five areas to update, we should investigate the dependency graph.</p><p>The solution might be:</p><ul><li>move state closer to consumers</li><li>use focused selectors</li><li>normalize state</li><li>memoize expensive derived data</li><li>separate components</li></ul><h3>Interview Follow-up Questions</h3><p><strong>Q: How does Redux cause unnecessary renders?</strong></p><p>Components re-render when the selected state changes according to the selector/equality behavior.</p><p><strong>Q: Why are focused selectors important?</strong></p><p>They reduce the amount of state a component subscribes to and make dependencies explicit.</p><p><strong>Q: What is state normalization?</strong></p><p>Representing relational data in a structured form, often by IDs, instead of deeply nested duplicated structures.</p><h3>9. Large Lists and Virtualization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jHvskrniWw0jGAoS" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*mLfyH94OcWMZngpV" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*EEFciW9VBEyTq0G1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MfHD9v_7pqX-k3GM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*qwprNhQ0VH0TzjLj" /></figure><p>Suppose we have:</p><pre>100,000 records</pre><p>Rendering every record creates a huge DOM.</p><p>Instead:</p><pre>100,000 records<br>      │<br>      ▼<br>Visible window<br>      │<br>      ▼<br>~30-100 DOM rows</pre><p>As the user scrolls, the rendered window changes.</p><p>This is virtualization/windowing.</p><p>It can dramatically reduce:</p><ul><li>DOM nodes</li><li>React work</li><li>layout</li><li>paint</li><li>memory</li></ul><h3>Interview Follow-up Questions</h3><p><strong>Q: When would you use virtualization?</strong></p><p>Large lists or grids where rendering every item creates measurable performance problems.</p><p><strong>Q: Does virtualization reduce the amount of data downloaded?</strong></p><p>No.</p><p>It primarily reduces the amount of UI rendered.</p><p>If the dataset itself is huge, server-side pagination or incremental loading may also be needed.</p><h3>10. Web Workers</h3><p>Some performance problems aren’t React problems at all.</p><p>Imagine processing a 5MB dataset:</p><pre>Parse<br> ↓<br>Transform<br> ↓<br>Group<br> ↓<br>Sort<br> ↓<br>Aggregate</pre><p>If this happens on the main thread, the UI can freeze.</p><p>A Web Worker allows suitable computation to run separately:</p><pre>Main Thread                Worker<br>     │                       │<br>     │──── Data ────────────►│<br>     │                       │<br>     │                  Heavy Processing<br>     │                       │<br>     │◄──── Result ──────────│<br>     │<br>     ▼<br>Update UI</pre><p>Good candidates include:</p><ul><li>CSV parsing</li><li>complex calculations</li><li>large transformations</li><li>data processing</li><li>computational algorithms</li></ul><h3>Interview Follow-up Questions</h3><p><strong>Q: What is a Web Worker?</strong></p><p>A separate JavaScript execution context that can perform work without blocking the main UI thread.</p><p><strong>Q: How do workers communicate?</strong></p><p>Typically through message passing.</p><p><strong>Q: What are the limitations?</strong></p><p>Workers don’t have direct access to the DOM and communication has overhead, especially when transferring/copying large data.</p><h3>11. Webpack Bundle Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r1kvO3Mwnrx3HPHc" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c4OmCuapyAeEDvwe" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*bq1diuqriSZGG1OY" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HRlIuw3HrPwsRh11" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*44Z6vvR-FjRHHeJu" /></figure><p>For Webpack applications, I want to know:</p><blockquote><strong><em>What exactly are we shipping to the browser?</em></strong></blockquote><p>A bundle might look conceptually like:</p><pre>Application<br>│<br>├── Chart Library      420KB<br>├── UI Library         300KB<br>├── Date Library       180KB<br>├── Editor             250KB<br>├── Application Code   350KB<br>└── Other              200KB</pre><p>Now we have an actionable problem.</p><p>Maybe the chart library is loaded on the dashboard even though charts are only required on /analytics.</p><h3>Code Splitting</h3><p>Instead of:</p><pre>import Analytics from &#39;./Analytics&#39;;</pre><p>we may use:</p><pre>const Analytics = lazy(<br>  () =&gt; import(&#39;./Analytics&#39;)<br>);</pre><p>This allows route-specific code to be loaded when needed.</p><h3>Interview Follow-up Questions</h3><p><strong>Q: What do you look for in Bundle Analyzer?</strong></p><ul><li>largest dependencies</li><li>duplicate dependencies</li><li>unnecessary initial dependencies</li><li>oversized application code</li><li>shared chunks</li><li>route-specific code</li><li>unexpected libraries</li></ul><p><strong>Q: What is tree shaking?</strong></p><p>Removing unused exports from a production bundle when the module system and build configuration allow it.</p><p><strong>Q: Dynamic import vs static import?</strong></p><p>Static imports are generally included in the normal dependency graph.</p><p>Dynamic imports create asynchronous loading boundaries.</p><p><strong>Q: Should we split every component?</strong></p><p>No.</p><p>Too much code splitting can create excessive chunks and network/request overhead.</p><p>The goal is meaningful loading boundaries.</p><h3>12. Webpack Caching</h3><p>A strong production configuration separates relatively stable vendor code from frequently changing application code.</p><p>Conceptually:</p><pre>Browser Cache</pre><pre>vendor.[hash].js<br>       +<br>app.[hash].js</pre><p>If only application code changes, the browser may continue using the cached vendor chunk.</p><p>This is one reason content hashing and long-lived caching strategies matter.</p><h3>Interview Follow-up Questions</h3><p><strong>Q: Why use content hashes in filenames?</strong></p><p>So changed assets get new URLs while unchanged assets remain cacheable.</p><p><strong>Q: What is long-term caching?</strong></p><p>Designing assets and cache headers so stable resources can remain cached for long periods while changed resources receive new URLs.</p><h3>13. Vite Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*ZKl_fPN9P_26F0LO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cfJV-u_88eo2U2V6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/0*_UHlAVoTtl87fSEx" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1hpuFOlFmKK05KmU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZhuR_Q1K1TPLFCF1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8bvpLKaGMFbyTyHA" /></figure><p>Vite changes the development experience significantly.</p><p>A simplified model:</p><pre>Traditional bundler development<br><br>Source<br> ↓<br>Bundle<br> ↓<br>Serve<br> ↓<br>Browser</pre><p>Vite development:</p><pre>Source<br> ↓<br>Native ESM<br> ↓<br>Browser requests modules<br> ↓<br>Transform as needed</pre><p>Vite also pre-bundles dependencies during development.</p><p>But an important distinction is:</p><blockquote><strong><em>Faster development tooling doesn’t automatically mean a faster production application.</em></strong></blockquote><p>Production still depends on:</p><ul><li>bundle size</li><li>chunking</li><li>dependencies</li><li>network</li><li>rendering</li><li>assets</li><li>architecture</li></ul><h3>Vite and Barrel Files</h3><p>Consider:</p><pre>import { formatDate } from &#39;@/utils&#39;;</pre><p>where:</p><pre>export * from &#39;./date&#39;;<br>export * from &#39;./string&#39;;<br>export * from &#39;./number&#39;;<br>export * from &#39;./currency&#39;;</pre><p>Sometimes direct imports can avoid unnecessary module loading/transformation:</p><pre>import { formatDate } from &#39;@/utils/date&#39;;</pre><p>This becomes increasingly relevant in large projects.</p><h3>Interview Follow-up Questions</h3><p><strong>Q: Why is Vite fast in development?</strong></p><p>Native ESM and dependency pre-bundling reduce the need to rebuild the entire application during development.</p><p><strong>Q: Is Vite faster than Webpack in production?</strong></p><p>That’s not a universal statement. Production performance depends on the generated output and application architecture.</p><p><strong>Q: What is dependency pre-bundling?</strong></p><p>Vite processes dependencies into a form optimized for development, including handling CommonJS/UMD dependencies and reducing module requests.</p><p><strong>Q: Can Vite eliminate performance problems?</strong></p><p>No. It is a build/development tool, not a substitute for performance profiling.</p><h3>14. Lighthouse</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xLk_Ey72etAAfxTh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t3-fO0Iu7Hxt1YTT" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Lq_5J4Bi8UrCKyR1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nypAn_aQckS78KXh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0o3e-ioS_vla13EJ" /></figure><p>Lighthouse is one of the first tools I use for controlled performance auditing.</p><p>It helps investigate:</p><blockquote>loading performance</blockquote><blockquote>performance opportunities</blockquote><blockquote>JavaScript</blockquote><blockquote>images</blockquote><blockquote>accessibility</blockquote><blockquote>best practices</blockquote><blockquote>SEO</blockquote><p>But I don’t treat:</p><pre>Lighthouse score = complete performance picture</pre><p>A score is a signal.</p><p>The real question is:</p><blockquote><strong><em>Which underlying metric or bottleneck caused the score?</em></strong></blockquote><h3>Interview Follow-up Questions</h3><p><strong>Q: Is Lighthouse enough to measure production performance?</strong></p><p>No.</p><p>It’s lab data.</p><p>Production requires field/RUM data.</p><p><strong>Q: What is the difference between lab and field data?</strong></p><p>Lab data is controlled and reproducible.</p><p>Field data represents real users and real conditions.</p><h3>15. Core Web Vitals</h3><p>The three major Core Web Vitals are:</p><pre>LCP → Loading<br>INP → Responsiveness<br>CLS → Visual Stability</pre><h3>LCP — Largest Contentful Paint</h3><p>Measures when the largest relevant content element becomes visible.</p><p>A good target is:</p><pre>≤ 2.5 seconds</pre><p>at the 75th percentile.</p><h3>INP — Interaction to Next Paint</h3><p>Measures responsiveness to user interactions.</p><p>A good target is:</p><pre>≤ 200ms</pre><p>at the 75th percentile.</p><h3>CLS — Cumulative Layout Shift</h3><p>Measures unexpected visual movement.</p><p>A good target is:</p><pre>≤ 0.1</pre><h3>Interview Follow-up Questions</h3><p><strong>Q: What are Core Web Vitals?</strong></p><p>LCP, INP and CLS.</p><p><strong>Q: Which metric replaced FID?</strong></p><p>INP.</p><p><strong>Q: What does LCP measure?</strong></p><p>Loading/rendering performance of the largest relevant visible content.</p><p><strong>Q: What causes poor INP?</strong></p><p>Usually excessive main-thread work around interactions, such as:</p><blockquote>expensive event handlers</blockquote><blockquote>long JavaScript tasks</blockquote><blockquote>excessive rendering</blockquote><blockquote>expensive DOM operations</blockquote><p><strong>Q: What causes CLS?</strong></p><p>Common examples:</p><blockquote>images without dimensions</blockquote><blockquote>dynamically inserted content</blockquote><blockquote>ads</blockquote><blockquote>fonts/layout changes</blockquote><blockquote>content shifting after initial rendering</blockquote><h3>16. Real LCP Example</h3><p>Suppose:</p><pre>LCP = 4.5 seconds</pre><p>The LCP element is a hero image.</p><p>The obvious reaction:</p><blockquote><em>Compress the image.</em></blockquote><p>But I investigate the entire chain:</p><pre>TTFB<br> ↓<br>HTML<br> ↓<br>Image discovery<br> ↓<br>Image request<br> ↓<br>Image download<br> ↓<br>Decode<br> ↓<br>Render</pre><p>If TTFB is already 2 seconds, optimizing a 200KB image may not solve the main issue.</p><h3>Interview Follow-up Question</h3><p><strong>Q: How would you debug poor LCP?</strong></p><p>I’d investigate:</p><ol><li>LCP element</li><li>TTFB</li><li>resource discovery</li><li>image/font loading</li><li>render-blocking resources</li><li>JavaScript execution</li><li>server/CDN performance</li></ol><h3>17. INP: When the Application Feels Frozen</h3><p>Consider:</p><pre>function handleBuy() {<br>  validateOrder();<br>  calculateRisk();<br>  updatePortfolio();<br>  refreshCharts();<br>  recalculatePositions();<br>  updateNotifications();<br>}</pre><p>If this takes 400ms:</p><pre>Click<br> ↓<br>400ms work<br> ↓<br>Browser can finally paint</pre><p>The button feels broken.</p><p>The goal isn’t necessarily to remove all work.</p><p>We ask:</p><blockquote><strong><em>What absolutely needs to happen before the next paint?</em></strong></blockquote><p>Then we can:</p><blockquote>split work</blockquote><blockquote>defer non-critical work</blockquote><blockquote>use transitions</blockquote><blockquote>move CPU-heavy work to a worker</blockquote><blockquote>optimize calculations</blockquote><blockquote>reduce rendering</blockquote><h3>Interview Follow-up Questions</h3><p><strong>Q: How would you diagnose poor INP?</strong></p><p>I’d use:</p><ul><li>Chrome Performance</li><li>long-task analysis</li><li>event handler profiling</li><li>React Profiler</li><li>production interaction data</li></ul><p>Then identify whether the bottleneck is:</p><pre>Event handler<br>    OR<br>JavaScript computation<br>    OR<br>React rendering<br>    OR<br>DOM/layout</pre><h3>18. CLS and Layout Stability</h3><p>Consider:</p><pre>&lt;img src=&quot;banner.jpg&quot; /&gt;</pre><p>without dimensions.</p><p>Initially:</p><pre>Article<br>Text<br>Button</pre><p>Then the image loads:</p><pre>Banner<br>Article<br>Text<br>Button</pre><p>Everything moves.</p><p>Reserve the space:</p><pre>&lt;img<br>  width=&quot;800&quot;<br>  height=&quot;400&quot;<br>  src=&quot;banner.webp&quot;<br>  alt=&quot;Banner&quot;<br>/&gt;</pre><h3>Interview Follow-up Questions</h3><p><strong>Q: How do you prevent CLS?</strong></p><ul><li>reserve image dimensions</li><li>reserve ad slots</li><li>avoid inserting content above existing content</li><li>manage font loading</li><li>avoid unexpected layout changes</li></ul><h3>19. API and Network Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F9B1ZJ95LmBYziQO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XClMmdyTAmJfGVrs" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*zuwFVrlbFdft2XmD" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cMKCxJQOswP6l-C_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/0*gZstPMy3hUdim3Yo" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qDDcpMmhe4chDcDb" /></figure><p>Suppose we have:</p><pre>/user<br>   ↓<br>/permissions<br>   ↓<br>/dashboard<br>   ↓<br>/charts<br>   ↓<br>/notifications</pre><p>If every request waits for the previous one:</p><pre>500ms<br>+ 300ms<br>+ 700ms<br>+ 600ms<br>+ 300ms<br><br>= 2.4 seconds</pre><p>If requests are independent:</p><pre>await Promise.all([<br>  getUser(),<br>  getPermissions(),<br>  getDashboard(),<br>  getCharts(),<br>  getNotifications()<br>]);</pre><p>we can often reduce the critical path.</p><p>But we shouldn’t parallelize requests that genuinely depend on each other.</p><h3>Interview Follow-up Questions</h3><p><strong>Q: What is an API waterfall?</strong></p><p>A sequence where one request waits for another unnecessarily.</p><p><strong>Q: How do you eliminate waterfalls?</strong></p><ul><li>parallelize independent requests</li><li>prefetch</li><li>cache</li><li>combine APIs where appropriate</li><li>move aggregation server-side</li><li>stream data</li><li>preload critical data</li></ul><p><strong>Q: HTTP/2 vs HTTP/3?</strong></p><p>A senior answer should discuss:</p><ul><li>multiplexing</li><li>connection behavior</li><li>HTTP/3 over QUIC</li><li>reduced head-of-line blocking characteristics</li><li>TLS/transport differences</li></ul><h3>20. Image Optimization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VxmsAwqi73DTnXOl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ILelH_1RpGdTkHQk" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*uJV5DD4-sYGgwiO5" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N7hFykEEU36g-JpX" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i7sFKeVBE-zB3q3K" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*8cANUlryWw7d0Zcf" /></figure><p>A 2MB image can be more expensive than several JavaScript modules.</p><p>I investigate:</p><ul><li>dimensions</li><li>format</li><li>compression</li><li>responsive sizes</li><li>lazy loading</li><li>loading priority</li><li>CDN transformations</li></ul><p>The important principle:</p><blockquote><em>Don’t send a 2000px image to a 390px device if the UI only needs a small version.</em></blockquote><h3>Interview Follow-up Questions</h3><p><strong>Q: WebP vs AVIF?</strong></p><p>Both provide modern image compression; AVIF can offer excellent compression but browser support, encoding cost and operational requirements should be considered.</p><p><strong>Q: Should every image be lazy-loaded?</strong></p><p>No.</p><p>Critical above-the-fold/LCP images may need priority rather than lazy loading.</p><p><strong>Q: Why specify image dimensions?</strong></p><p>To reserve layout space and reduce CLS.</p><h3>21. Fonts</h3><p>Fonts can affect both loading and layout.</p><p>I review:</p><pre>Font families<br>Weights<br>WOFF2<br>Subsets<br>Preload<br>font-display</pre><p>If the application uses only:</p><pre>400<br>600</pre><p>there is little reason to download nine font weights.</p><h3>Interview Follow-up Questions</h3><p><strong>Q: How can fonts affect performance?</strong></p><p>They can introduce additional requests, delay text rendering and cause layout changes.</p><p><strong>Q: What is </strong><strong>font-display?</strong></p><p>It controls how text behaves while the web font is loading.</p><h3>22. Third-Party JavaScript</h3><p>Examples:</p><pre>Analytics<br>Chat<br>A/B testing<br>Tracking<br>Advertising<br>Support widgets</pre><p>For each script I ask:</p><pre>Do we need it?<br>When do we need it?<br>Can it load later?<br>Can it load conditionally?<br>Can we remove it?</pre><p>Third-party scripts can consume CPU and network resources even though they don’t belong to our application code.</p><h3>Interview Follow-up Questions</h3><p><strong>Q: How do you optimize third-party scripts?</strong></p><ul><li>defer</li><li>lazy initialize</li><li>load after interaction</li><li>conditionally load</li><li>remove unnecessary scripts</li><li>consolidate tooling where possible</li></ul><h3>23. Memory Leaks</h3><p>Not all performance issues appear during the first page load.</p><p>A SPA can progressively degrade:</p><pre>Open Dashboard<br> ↓<br>Reports<br> ↓<br>Dashboard<br> ↓<br>Reports<br> ↓<br>Repeat</pre><p>If every page leaves behind:</p><ul><li>listeners</li><li>timers</li><li>subscriptions</li><li>WebSockets</li><li>observers</li></ul><p>memory can grow continuously.</p><h3>Example</h3><p>Bad:</p><pre>useEffect(() =&gt; {<br>  window.addEventListener(<br>    &#39;resize&#39;,<br>    handleResize<br>  );<br>}, []);</pre><p>Better:</p><pre>useEffect(() =&gt; {<br>  window.addEventListener(<br>    &#39;resize&#39;,<br>    handleResize<br>  );<br><br>return () =&gt; {<br>    window.removeEventListener(<br>      &#39;resize&#39;,<br>      handleResize<br>    );<br>  };<br>}, []);</pre><p>The same principle applies to:</p><pre>setInterval<br>setTimeout<br>WebSocket<br>IntersectionObserver<br>ResizeObserver<br>subscriptions</pre><h3>Interview Follow-up Questions</h3><p><strong>Q: How do you detect memory leaks?</strong></p><p>Use:</p><ul><li>Chrome Memory panel</li><li>heap snapshots</li><li>allocation timelines</li><li>detached DOM inspection</li><li>repeated navigation testing</li></ul><p><strong>Q: What are common causes?</strong></p><ul><li>unremoved listeners</li><li>subscriptions</li><li>timers</li><li>closures retaining objects</li><li>global references</li><li>WebSocket connections</li><li>detached DOM</li></ul><h3>24. SSR, CSR, SSG and Streaming</h3><p>Rendering architecture directly affects performance.</p><h3>CSR</h3><pre>HTML<br> ↓<br>JavaScript<br> ↓<br>React<br> ↓<br>Data<br> ↓<br>UI</pre><h3>SSR</h3><pre>Request<br> ↓<br>Server renders HTML<br> ↓<br>Browser receives HTML<br> ↓<br>Hydration<br> ↓<br>Interactive</pre><h3>SSG</h3><pre>Build<br> ↓<br>Generate HTML<br> ↓<br>CDN<br> ↓<br>User</pre><h3>Streaming</h3><pre>Server<br> │<br> ├── Send critical UI<br> ├── Continue rendering<br> └── Stream remaining content</pre><p>There is no universally best rendering strategy.</p><h3>Interview Follow-up Questions</h3><p><strong>Q: SSR vs CSR?</strong></p><p>SSR can improve initial content delivery and SEO in appropriate applications, while CSR provides a client-centric model after JavaScript loads.</p><p><strong>Q: Does SSR eliminate JavaScript cost?</strong></p><p>No.</p><p>The browser may still need to hydrate interactive components.</p><p><strong>Q: What is hydration?</strong></p><p>Connecting client-side behavior to server-rendered HTML.</p><h3>25. Hydration Performance</h3><p>A page can look fast:</p><pre>HTML arrives<br> ↓<br>Content visible</pre><p>but still feel unresponsive:</p><pre>HTML<br> ↓<br>Large JS<br> ↓<br>Parse<br> ↓<br>Compile<br> ↓<br>Execute<br> ↓<br>Hydrate<br> ↓<br>Interactive</pre><p>This is why:</p><blockquote><strong><em>Visual loading and interactivity are different problems.</em></strong></blockquote><h3>Interview Follow-up Questions</h3><p><strong>Q: Why can SSR pages still have poor INP?</strong></p><p>Because large client-side JavaScript and hydration can still consume the main thread.</p><p><strong>Q: How can we reduce hydration cost?</strong></p><ul><li>reduce client-side JavaScript</li><li>move logic server-side where appropriate</li><li>reduce client boundaries</li><li>lazy-load interactive sections</li><li>use framework capabilities such as server components where appropriate</li></ul><h3>26. Next.js and Client Boundaries</h3><p>A common mistake is putting:</p><pre>&#39;use client&#39;;</pre><p>too high in the component tree.</p><p>That can turn a large subtree into client-side code.</p><p>A better architecture can be:</p><pre>Server Component<br>      │<br>      ├── Server-rendered content<br>      │<br>      └── Small Client Component</pre><p>The goal:</p><blockquote><em>Keep JavaScript close to the interaction that actually requires it.</em></blockquote><h3>Interview Follow-up Questions</h3><p><strong>Q: What happens when you mark a high-level component as client-side?</strong></p><p>A larger portion of the component tree may become part of the client-side dependency graph.</p><p><strong>Q: How do you decide where the client boundary should be?</strong></p><p>Place it around the smallest subtree that actually needs client-side state, effects or browser APIs.</p><h3>27. Performance Budgets</h3><p>Performance shouldn’t only be checked manually.</p><p>I prefer defining budgets.</p><p>For example:</p><pre>Initial JS       &lt; 250KB compressed<br>Initial CSS      &lt; 100KB<br>LCP              &lt; 2.5s<br>INP              &lt; 200ms<br>CLS              &lt; 0.1</pre><p>These aren’t universal values.</p><p>The correct budget depends on the product.</p><p>The important part is:</p><blockquote><strong><em>Performance should become a measurable engineering requirement.</em></strong></blockquote><h3>Interview Follow-up Questions</h3><p><strong>Q: How would you prevent a developer from accidentally adding 500KB to the bundle?</strong></p><p>I’d introduce:</p><ul><li>bundle-size checks</li><li>CI performance budgets</li><li>bundle diff</li><li>Lighthouse CI</li><li>pull-request reporting</li></ul><h3>28. CI/CD Performance</h3><p>A mature workflow:</p><pre>Pull Request<br>      ↓<br>Production Build<br>      ↓<br>Bundle Analysis<br>      ↓<br>Bundle Diff<br>      ↓<br>Lighthouse CI<br>      ↓<br>Performance Budget<br>      │<br>      ├── FAIL → Fix<br>      │<br>      ▼<br>     PASS<br>      ↓<br>   Deploy<br>      ↓<br>     RUM</pre><p>This changes performance from:</p><blockquote><em>“Someone checks it occasionally.”</em></blockquote><p>to:</p><blockquote><strong><em>“Performance is continuously protected.”</em></strong></blockquote><h3>Interview Follow-up Questions</h3><p><strong>Q: Should performance tests block CI?</strong></p><p>For important regression thresholds, yes — but budgets should be calibrated to avoid noisy failures.</p><p><strong>Q: What should trigger a failure?</strong></p><p>Potentially:</p><ul><li>bundle growth</li><li>LCP regression</li><li>performance score regression</li><li>excessive JS</li><li>failed Core Web Vital thresholds</li></ul><h3>29. Real Production Case Study</h3><p>Let’s put everything together.</p><p>Imagine an analytics platform.</p><p>The complaint:</p><blockquote><strong><em>“Dashboard takes too long to load and filters are laggy.”</em></strong></blockquote><h3>Initial measurement</h3><pre>LCP              4.1s<br>INP              420ms<br>CLS              0.19<br><br>JS               1.8MB<br>DOM              14,000 nodes<br>Requests         61</pre><blockquote>Step 1 — Bundle Analysis</blockquote><p>We find:</p><pre>Chart Library     430KB<br>UI Library        290KB<br>Date Library      180KB<br>Editor            240KB<br>App Code          360KB</pre><p>Charts are loaded even when the chart tab isn’t opened.</p><h3>Fix</h3><p>Route-level lazy loading.</p><blockquote>Step 2 — React Profiler</blockquote><p>Filtering causes:</p><pre>Filter<br> ↓<br>Dashboard<br> ↓<br>Chart<br> ↓<br>Table<br> ↓<br>Activity<br> ↓<br>Notifications</pre><h3>Root cause</h3><p>State is too high in the component tree.</p><h3>Fix</h3><p>Move state closer to consumers.</p><blockquote>Step 3 — Table</blockquote><p>The table renders:</p><pre>8,000 rows</pre><h3>Fix</h3><p>Virtualization.</p><blockquote>Step 4 — Data Processing</blockquote><p>A 4MB response is processed synchronously.</p><h3>Fix</h3><p>Reduce the payload and move suitable heavy computation to a worker.</p><blockquote>Step 5 — API Waterfall</blockquote><pre>User<br> ↓<br>Permissions<br> ↓<br>Dashboard<br> ↓<br>Charts</pre><p>Some requests are independent.</p><h3>Fix</h3><p>Parallelize independent calls.</p><blockquote>Step 6 — Images</blockquote><p>Hero image:</p><pre>2.1MB</pre><h3>Fix</h3><ul><li>responsive images</li><li>modern format</li><li>CDN transformation</li><li>correct dimensions</li></ul><blockquote>Step 7 — Third-Party Scripts</blockquote><p>Non-critical scripts initialize immediately.</p><h3>Fix</h3><p>Defer initialization where product requirements allow.</p><h3>30. Results</h3><p>After optimization:</p><pre>Metric              Before       After<br><br>LCP                  4.1s         2.0s<br>INP                  420ms        145ms<br>CLS                  0.19         0.04<br>JS                   1.8MB        720KB<br>DOM                  14,000       3,200<br>Requests             61           27<br>Table rows rendered  8,000        ~50</pre><p>The important lesson isn’t the numbers.</p><p>It’s the process:</p><pre>Measure<br>   ↓<br>Profile<br>   ↓<br>Find root cause<br>   ↓<br>Optimize<br>   ↓<br>Measure again</pre><h3>31. What I Would NOT Do</h3><p>I wouldn’t start with:</p><pre>❌ Add useMemo everywhere<br>❌ Add React.memo everywhere<br>❌ Switch Webpack to Vite just for performance<br>❌ Lazy-load every component<br>❌ Compress every image blindly<br>❌ Add a CDN without understanding caching<br>❌ Blame React for browser layout problems<br>❌ Trust only Lighthouse<br>❌ Trust only bundle size<br>❌ Optimize without a baseline</pre><p>The tools are not the strategy.</p><p><strong>Diagnosis is the strategy.</strong></p><h3>32. My Performance Decision Tree</h3><pre>            APPLICATION IS SLOW<br>                       │<br>             ┌─────────┴─────────┐<br>             │                   │<br>          Loading             Interaction<br>             │                   │<br>             ▼                   ▼<br>          LCP/TTFB              INP<br>             │                   │<br>       ┌─────┼─────┐       ┌────┼────┐<br>       ▼     ▼     ▼       ▼    ▼    ▼<br>     Server  JS   Assets    JS  React DOM<br>       │     │     │        │    │    │<br>       ▼     ▼     ▼        ▼    ▼    ▼<br>     API   Bundle Images   Tasks Fiber Layout<br>     CDN   Chunks Fonts    CPU   Render Paint</pre><p>This is the mental model I use when investigating performance.</p><h3>33. Performance by Layer</h3><p>LayerQuestionsServerIs TTFB high?CDNAre assets cached?NetworkAre requests sequential?HTMLIs critical content available early?CSSIs rendering blocked?ImagesAre assets oversized?FontsAre too many fonts loaded?JavaScriptHow much are we downloading/executing?WebpackWhat is inside the bundle?ViteAre dependencies/chunks optimized?ReactWhy are components rendering?FiberHow is rendering work scheduled?ReduxAre subscriptions too broad?DOMIs the tree unnecessarily large?BrowserIs layout/paint expensive?WorkersCan CPU work leave the main thread?CacheAre we re-downloading resources?RUMWhat do real users experience?</p><h3>34. The Complete Frontend Performance Toolkit</h3><pre>                 PERFORMANCE<br>                      │<br>       ┌──────────────┼──────────────┐<br>       ▼              ▼              ▼<br>    Browser         React          Build<br>       │              │              │<br>   DevTools        Profiler       Webpack<br>   Network         Fiber          Vite<br>   Performance     Rendering      Bundle<br>   Memory          Redux          Chunks<br>       │              │              │<br>       └──────────────┼──────────────┘<br>                      ▼<br>                   Network<br>                      │<br>                API / CDN / Cache<br>                      │<br>                      ▼<br>                   Metrics<br>                      │<br>            Lighthouse / RUM<br>                      │<br>                      ▼<br>                 Production</pre><h3>35. Senior-Level Interview Questions</h3><p>If I’m interviewing a <strong>10+ year frontend engineer</strong>, I wouldn’t stop at:</p><blockquote><em>“What is </em><em>useMemo?&quot;</em></blockquote><p>I’d ask questions such as:</p><h3>Architecture</h3><ol><li>How would you design a frontend application for performance from day one?</li><li>How would you define performance budgets?</li><li>How would you handle a dashboard with 50,000 concurrent users?</li><li>How would you architect a real-time trading interface?</li><li>How do you decide between CSR, SSR, SSG and streaming?</li></ol><h3>React</h3><ol><li>Explain React Fiber.</li><li>Explain render vs commit.</li><li>Why is a component re-rendering?</li><li>When would you use React.memo?</li><li>When would you avoid useMemo?</li><li>useMemo vs useCallback.</li><li>useTransition vs useDeferredValue.</li><li>How would you optimize a large React table?</li><li>How would you debug unnecessary renders?</li></ol><h3>Redux</h3><ol><li>How can Redux cause performance problems?</li><li>How would you optimize selectors?</li><li>What is state normalization?</li><li>How would you structure state for a large dashboard?</li></ol><h3>Webpack</h3><ol><li>How do you investigate a 2MB bundle?</li><li>How does tree shaking work?</li><li>What is code splitting?</li><li>Dynamic import vs static import?</li><li>How would you design caching?</li><li>How do you use Bundle Analyzer?</li></ol><h3>Vite</h3><ol><li>Why is Vite fast in development?</li><li>What is dependency pre-bundling?</li><li>How does Vite differ from Webpack?</li><li>Can migrating to Vite automatically improve production performance?</li><li>What are barrel files and why can they matter?</li></ol><h3>Browser</h3><ol><li>Explain the browser rendering pipeline.</li><li>What causes layout thrashing?</li><li>Layout vs paint vs composite?</li><li>What is a long task?</li><li>What blocks the main thread?</li></ol><h3>Core Web Vitals</h3><ol><li>Explain LCP.</li><li>Explain INP.</li><li>Explain CLS.</li><li>How would you debug poor LCP?</li><li>How would you debug poor INP?</li><li>What causes CLS?</li></ol><h3>Network</h3><ol><li>How do you identify an API waterfall?</li><li>How would you optimize 20 API requests?</li><li>HTTP/1.1 vs HTTP/2 vs HTTP/3?</li><li>How would you use browser caching?</li><li>CDN vs browser cache?</li></ol><h3>Runtime</h3><ol><li>When would you use Web Workers?</li><li>How do you identify memory leaks?</li><li>What causes SPA memory leaks?</li><li>How would you debug a page that becomes slower after one hour?</li></ol><h3>Production</h3><ol><li>How do you monitor frontend performance in production?</li><li>Lab vs field performance?</li><li>How would you introduce performance checks into CI/CD?</li><li>How do you prevent bundle-size regressions?</li><li>How do you measure whether an optimization actually helped?</li></ol><h3>36. The Questions I’d Expect in a Lead-Level Interview</h3><p>For a <strong>Lead Frontend Developer</strong>, interviewers will often go beyond definitions.</p><p>They may give you a scenario:</p><blockquote><strong><em>“Our React dashboard has 20 charts, a 10,000-row table and real-time updates. Users complain that filtering freezes the browser. What would you do?”</em></strong></blockquote><p>A strong answer shouldn’t immediately say:</p><blockquote><em>“I’ll use </em><em>useMemo.&quot;</em></blockquote><p>Instead:</p><pre>1. Reproduce<br>       ↓<br>2. Measure INP<br>       ↓<br>3. Chrome Performance<br>       ↓<br>4. React Profiler<br>       ↓<br>5. Identify main-thread work<br>       ↓<br>6. Check Redux subscriptions<br>       ↓<br>7. Check table virtualization<br>       ↓<br>8. Check chart rendering frequency<br>       ↓<br>9. Move heavy calculations to Worker<br>       ↓<br>10. Reduce unnecessary renders<br>       ↓<br>11. Measure again</pre><p>That demonstrates <strong>engineering thinking</strong>, not just API knowledge.</p><h3>37. The Most Important Questions to Ask Yourself</h3><p>Whenever I see a performance issue, I ask:</p><h3>1. Are we downloading too much?</h3><pre>Bundle<br>Images<br>Fonts<br>API payloads<br>Third-party scripts</pre><h3>2. Are we executing too much?</h3><pre>JavaScript<br>React renders<br>Data processing<br>Third-party code</pre><h3>3. Are we rendering too much?</h3><pre>DOM<br>Lists<br>Charts<br>Components</pre><h3>4. Are we doing work too early?</h3><pre>Non-critical JavaScript<br>Images<br>API calls<br>Hydration<br>Third-party scripts</pre><h3>5. Are we doing work repeatedly?</h3><pre>Calculations<br>Rendering<br>Selectors<br>Network requests<br>Layout</pre><h3>6. Can we avoid the work entirely?</h3><p>This is usually the most powerful question.</p><h3>38. Final Takeaway</h3><p>After 10+ years of frontend engineering, my approach to performance can be summarized in one sentence:</p><blockquote><strong><em>Measure first, find the real bottleneck, optimize the root cause, and validate the result with real data.</em></strong></blockquote><blockquote>React Fiber matters.</blockquote><blockquote>Webpack matters.</blockquote><blockquote>Vite matters.</blockquote><blockquote>Lighthouse matters.</blockquote><blockquote>Core Web Vitals matter.</blockquote><blockquote>Redux matters.</blockquote><blockquote>Caching matters.</blockquote><blockquote>Web Workers matter.</blockquote><blockquote>But none of these is a silver bullet.</blockquote><p>The real skill is knowing <strong>which layer is responsible for the problem you’re seeing</strong>.</p><blockquote>A slow dashboard isn’t automatically a React problem.</blockquote><blockquote>A large bundle isn’t automatically a Webpack problem.</blockquote><blockquote>A poor LCP isn’t automatically an image problem.</blockquote><blockquote>A poor INP isn’t automatically a React problem.</blockquote><blockquote>A slow application after an hour isn’t necessarily a rendering problem — it may be a memory leak.</blockquote><blockquote>Performance engineering is therefore not about collecting optimization tricks.</blockquote><p>It’s about understanding the entire system:</p><pre>Architecture<br>     +<br>Network<br>     +<br>Server<br>     +<br>CDN<br>     +<br>Assets<br>     +<br>JavaScript<br>     +<br>Webpack / Vite<br>     +<br>React / Fiber<br>     +<br>DOM<br>     +<br>Browser<br>     +<br>Caching<br>     +<br>Monitoring</pre><p>And the principle I keep coming back to is:</p><blockquote><strong><em>The fastest code is often the code that never needs to run.</em></strong></blockquote><p>Follow me for more such content .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73db8bc5322e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>