<?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 Sayahayoub on Medium]]></title>
        <description><![CDATA[Stories by Sayahayoub on Medium]]></description>
        <link>https://medium.com/@sayahayoub9827?source=rss-3d2951eacd9e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gGa0lMyhSIklYSH0X_i4Bg.jpeg</url>
            <title>Stories by Sayahayoub on Medium</title>
            <link>https://medium.com/@sayahayoub9827?source=rss-3d2951eacd9e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 00:34:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sayahayoub9827/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[The Real Cost of Styling: What Actually Happens in the Browser]]></title>
            <link>https://javascript.plainenglish.io/the-real-cost-of-styling-what-actually-happens-in-the-browser-0170492611f5?source=rss-3d2951eacd9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0170492611f5</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[chakra-ui]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Sayahayoub]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 23:26:29 GMT</pubDate>
            <atom:updated>2026-07-14T07:10:51.881Z</atom:updated>
            <content:encoded><![CDATA[<p>If you look at the debates around frontend styling today, almost everyone focuses on the syntax. <em>Do you like writing massive lists of utility classes? Do you prefer the isolation of scoped CSS modules? Or do you want to pass styles directly as React props?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PY3sWfltKTHRAaAcZI4_dg.png" /></figure><p>But arguing over syntax completely misses the point. The real difference between these tools isn’t how they look in your IDE — it’s how they interact with the browser’s rendering engine and whether it plays nice with modern framework architectures..</p><p>Right now, the modern frontend landscape is dominated by three main philosophies:</p><p>1. <strong>Runtime CSS-in-JS</strong> (Chakra UI,Material Ui,Ant Design…, running on top of Emotion)</p><p>2. <strong>Utility-First CSS</strong> (Tailwind CSS)</p><p>3. <strong>Traditional CSS</strong> (CSS Modules and frameworks like Bootstrap)</p><p>Instead of just debating developer preference, I wanted to see what these tools actually cost your application. To do that, we need to dive directly into the browser’s layout and paint pipelines, examine how they handle dynamic style injection, and run some real benchmarks.</p><p><strong>The Contenders: The Good, The Bad, and The Syntax</strong></p><p>Before we start arguing about performance, let’s look at who we’re dealing with.</p><p><strong>Chakra UI &amp; Emotion (Runtime CSS-in-JS)</strong></p><p>You write your CSS directly inside your JavaScript. Chakra UI is basically a massive library of accessible Lego-block components built directly on top of the Emotion engine. Emotion does the heavy lifting, processing your styles dynamically while the app is running.</p><ul><li><strong>Pros:</strong> The developer experience is genuinely incredible. You get dynamic theming out of the box, you never have to worry about class name collisions, and prototyping a dashboard with Chakra is stupidly fast.</li><li><strong>The Catch:</strong> <em>It requires a heavy JavaScript runtime, and </em><strong><em>it is fundamentally incompatible with modern React Server Components (RSCs)</em></strong><em>. Because it relies on a client-side context provider, you cannot use runtime CSS-in-JS on the server.</em></li></ul><p><strong>Tailwind CSS (Utility-First CSS)</strong></p><p>No more CSS files. You just write short utility classes directly in your HTML or JSX (stuff like `flex items-center p-4`).</p><ul><li><strong>Pros: </strong>It’s crazy fast once you learn it. You don’t have to jump between files, your CSS bundle stops growing after a certain point because you’re just reusing the same utilities, and there is absolutely zero JavaScript overhead at runtime.</li></ul><p><strong>CSS Modules &amp; Bootstrap (Traditional CSS)</strong></p><p>The old reliable. CSS Modules give you scoped stylesheets so you don’t leak global styles, while Bootstrap hands you pre-made classes (`.btn-primary`) to slap onto your elements.</p><ul><li><strong>Pros:</strong> Zero magic. No weird build steps or steep learning curves. If you know CSS, you know how to use this.</li></ul><p><strong>What Actually Happens in the Browser? (The Performance Cost)</strong></p><p>This is where things get interesting. To understand why your app might feel sluggish, you have to look at what the browser is doing.</p><p>When Chrome or Safari loads your page, it parses your HTML into a DOM tree and your CSS into a CSSOM tree. Then it mashes them together in a <strong>Style Recalculation</strong> phase, figures out the layout, and paints pixels to your screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wd6UhVbe7ui_Ul4pwExRwg.png" /></figure><p><strong>The Single-Thread Bottleneck</strong></p><p>Here’s the most critical piece of the puzzle: the browser’s <strong>Main Thread is heavily bottlenecked</strong>. It has to execute your JavaScript, calculate styles, build the layout tree, and generate the paint records <em>all on the exact same thread</em>. (While the actual rasterization of pixels is offloaded to the GPU/Compositor thread, the main thread has to finish its work before the GPU can draw anything).</p><p>With <strong>Tailwind</strong> or <strong>CSS Modules</strong>, the browser parses the static CSS file in parallel while downloading, caches the CSSOM, and it’s done. The main thread’s JavaScript engine is free to just handle user interactions.</p><p>With <strong>Emotion (CSS-in-JS)</strong>, things get messy. Because it generates styles dynamically, it forces the browser to play a game of stop-and-go:</p><p>1. React starts rendering, executing your component’s JavaScript.</p><p>2. Emotion evaluates your props, runs a JS-to-CSS transformation, hashes the result, and injects it into the DOM via <strong>sheet.insertRule</strong>.</p><p>3. Because new CSS was just injected, the browser has to throw away its style cache and rebuild the layout tree.</p><p>⚠️ <strong>The Core Web Vitals Hit:</strong> <em>This JS-to-CSS transformation blocks the main thread. If a user clicks a button or tries to scroll while JavaScript is calculating CSS math, the interaction gets queued up. This directly tanks your </em><strong><em>Interaction to Next Paint (INP)</em></strong><em> metric, causing noticeable micro-stutters.</em></p><p>Chakra UI makes this worse. Because everything is a styled primitive (like a `&lt;Box&gt;`), every single prop you pass has to run through a JavaScript resolution loop.</p><p><strong>Let’s look at some Benchmarks</strong></p><p>I ran a test rendering 1,000 simple list items to see how much this runtime tax actually costs.</p><p>Render Time for 1,000 Items (Lower is Better)</p><p>Tailwind CSS ████░░░░░░░░░░░░░░░░ 30ms</p><p>CSS Modules ████░░░░░░░░░░░░░░░░ 30ms</p><p>Emotion ███████████░░░░░░░░░ 85ms</p><p>Chakra UI ████████████████████ 140ms</p><p>Yeah. Rendering a massive grid in Chakra takes roughly 4 to 5 times longer than just using Tailwind or standard CSS. If performance is your absolute top priority, runtime CSS-in-JS is going to hurt you.</p><p>In fact, this runtime tax is exactly why the creators of Chakra UI are shifting away from it. In Chakra v3, they completely ditched @emotion/styled and framer-motion to strip out massive runtime bloat. They rebuilt their entire core around a new token system inspired by Panda CSS (createSystem). While they still temporarily route styles through @emotion/react at runtime during this transitional phase, their explicitly stated roadmap is to completely phase out the runtime engine for a zero-runtime model</p><p>On top of that, Tailwind completely purges unused classes at build time. It only ships what you actually use. But there’s a catch: because it runs at build time, dynamic classes don’t work. If you try to do `className={“bg-” + myColor + “-500”}`, Tailwind won’t see it, and it’ll break. Emotion handles dynamic stuff flawlessly.</p><p>And don’t get me started on raw CSS. Sure, it’s fast, but managing a massive CSS codebase is a nightmare. Developers get terrified of deleting classes because they don’t know what will break, so the CSS files just grow forever. It becomes this massive, bloated append-only file that eventually drags down your page load speed anyway.</p><p><strong>Writing Code: The Developer Experience</strong></p><p>Performance isn’t everything. Sometimes shipping a feature today is more important than saving 40 milliseconds.</p><p><strong>Onboarding</strong></p><p>Bootstrap and CSS Modules are basically free. Everyone knows them. Emotion isn’t too hard if you understand JS template literals. But Tailwind? Tailwind is rough for the first two weeks. You have to memorize a whole new dictionary of utility classes. It feels terrible at first, but once you get it, you’ll never want to go back.</p><p><strong>The Tooling</strong></p><p>Tailwind’s IntelliSense plugin is practically magic. You start typing and it instantly shows you exactly what CSS it’s applying. Chakra is fully typed in TypeScript, so you get incredible autocomplete right on your React props. CSS Modules feel a bit dated here — jumping between your `.tsx` file and your `.css` file constantly breaks my flow.</p><p><strong>Shipping Speed</strong></p><p>If I need to build an admin dashboard by Friday, I’m reaching for Chakra UI. The pre-built, accessible components mean I don’t even have to think about design. If I’m building a highly custom landing page where every pixel matters, Tailwind lets me move incredibly fast without fighting framework overrides.</p><p>To really compare them, I built a simple interactive Button with hover, active, loading, and disabled states.</p><p><strong>1. Chakra UI (Built on Emotion)</strong></p><p>You don’t even need a stylesheet. You just pass props.</p><pre>import { Button } from &quot;@chakra-ui/react&quot;;<br>export function MyButton({ variant, isLoading, children }) {<br>return (<br>&lt;Button<br>colorScheme={variant === &quot;primary&quot; ? &quot;blue&quot; : &quot;gray&quot;}<br>isLoading={isLoading}<br>loadingText=&#39;Wait for it…&#39;<br>px={6}<br>py={3}<br>transition=&#39;all 0.2s&#39;<br>_hover={{ transform: &quot;translateY(-1px)&quot; }}<br>_active={{ transform: &quot;translateY(1px)&quot; }}<br>&gt;<br>{children}<br>&lt;/Button&gt;<br>);<br>}</pre><p><strong>2. Tailwind CSS</strong></p><p>It looks messy at first glance, but notice how everything is right there in the markup.</p><pre>export function MyButton({ variant, isLoading, children }) {<br>const base =<br>&quot;inline-flex items-center px-6 py-3 font-semibold text-white rounded-lg transition-all duration-200&quot;;<br>const colors =<br>variant === &quot;primary&quot;<br>? &quot;bg-blue-500 hover:bg-blue-600 active:translate-y-0.5&quot;<br>: &quot;bg-gray-400 hover:bg-gray-500 active:translate-y-0.5&quot;;<br>const state = isLoading ? &quot;opacity-70 cursor-not-allowed&quot; : &quot;cursor-pointer&quot;;<br>return (<br>&lt;button disabled={isLoading} className={`${base} ${colors} ${state}`}&gt;<br>{isLoading ? &quot;Wait for it…&quot; : children}<br>&lt;/button&gt;<br>);<br>}</pre><p><strong>3. CSS Modules</strong></p><p>The classic split.</p><pre>.btn {<br>padding: 12px 24px;<br>font-weight: 600;<br>color: white;<br>border-radius: 8px;<br>border: none;<br>transition: all 0.2s;<br>cursor: pointer;<br>}<br>.primary {<br>background-color: #3b82f6;<br>}<br>.primary:hover:not(:disabled) {<br>background-color: #2563eb;<br>transform: translateY(-1px);<br>}<br>.loading {<br>opacity: 0.7;<br>cursor: not-allowed;<br>}</pre><pre>import styles from &quot;./button.module.css&quot;;<br>export function MyButton({ variant, isLoading, children }) {<br>const themeClass = variant === &quot;primary&quot; ? styles.primary : styles.secondary;<br>return (<br>&lt;button<br>className={`${styles.btn} ${themeClass} ${isLoading ? styles.loading : &quot;&quot;}`}<br>disabled={isLoading}<br>&gt;<br>{isLoading ? &quot;Wait for it…&quot; : children}<br>&lt;/button&gt;<br>);<br>}</pre><p><strong>So, what should you actually use?</strong></p><p>Look, there is no single “perfect” stack. Anyone who tells you otherwise is probably trying to sell you a course. Choosing the right tool depends entirely on what your team actually cares about.</p><p>-<strong>Choose Tailwind CSS</strong> <em>if you are building public-facing web apps, e-commerce sites, or using modern frameworks like Next.js that leverage React Server Components. It ensures the smallest possible bundle size and unmatched main-thread performance.</em></p><p>- <strong>Go with Chakra UI &amp; Emotion </strong>if you’re building a heavily dynamic dashboard behind a login screen where SEO doesn’t matter, and you just want to ship accessible UI components as fast as humanly possible.</p><p>- <strong>Go with CSS Modules or Bootstrap</strong> if you hate build tools, don’t want to learn new syntax, or you’re working in a legacy codebase that just needs to be stable.</p><h3>But wait, there is also a middle ground…</h3><p>If you read this and thought, <em>“I want the raw performance of Tailwind, but I absolutely refuse to give up my type-safe component props,”</em> there is also an emerging fourth category: <strong>Zero-Runtime, Build-Time CSS-in-JS</strong> (like Vanilla Extract, Panda CSS, or StyleX).</p><p>These tools give you the exact same developer experience as Emotion, but they do all the heavy lifting during your build step, spitting out static CSS files before the code ever touches a user’s browser. It bridges the gap perfectly, giving you the DX of CSS-in-JS with the runtime speed and RSC compatibility of Tailwind.</p><p>At the end of the day, choose the architecture that matches your project constraints, and use the tool that gets you away from the keyboard and out living your life faster.</p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0170492611f5" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-real-cost-of-styling-what-actually-happens-in-the-browser-0170492611f5">The Real Cost of Styling: What Actually Happens in the Browser</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shrinking Your SPA’s Entry Bundle: The Key to Faster Loads]]></title>
            <link>https://medium.com/@sayahayoub9827/shrinking-your-spas-entry-bundle-the-key-to-faster-loads-3db155d5c6b2?source=rss-3d2951eacd9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3db155d5c6b2</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Sayahayoub]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 13:14:58 GMT</pubDate>
            <atom:updated>2025-08-13T13:15:47.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Single Page Applications often suffer from slow initial loads because they send a massive JavaScript bundle upfront — even code users don’t immediately need.</p><p>Google’s key performance rule? Keep that initial JS payload small.</p><p>In this article, we’ll see why SPAs struggle with this, how to analyze your bundle, and practical tips to cut down your entry file for faster loading and better user experience.</p><h3>Section 1 — Google’s First Performance Rule That Everyone Ignores</h3><p>If you’ve ever looked at Google’s web performance checklist, the first thing they hammer on is this:</p><blockquote><strong><em>Keep your initial JavaScript payload small.</em></strong></blockquote><p>It sounds obvious, but most single-page applications (SPAs) fail here… badly.</p><p>Google doesn’t say this to be picky. Big JS bundles kill load times. Before a single pixel shows up on screen, the browser has to:</p><ol><li>Download all that code.</li><li>Parse and compile it on the main thread.</li><li>Run it before anything becomes interactive.</li></ol><p>That’s why Lighthouse loves to yell things like <strong>“Reduce JavaScript execution time”</strong> or <strong>“Eliminate render-blocking resources”</strong> — because your user is literally staring at a blank or frozen screen while the browser chews through your code.</p><p>And it’s not just about “fast internet vs. slow internet.” Even on a fiber connection, a big entry bundle delays <strong>LCP</strong> (Largest Contentful Paint), <strong>FID</strong> (First Input Delay), and <strong>TTI</strong> (Time To Interactive).</p><h3>Section 2 — Why SPAs Are So Bad at Following This Rule</h3><p>The problem isn’t that SPA developers don’t know about Google’s “small JS” rule.<br> The problem is that the way most SPAs are built almost <em>guarantees</em> we break it.</p><p>Here’s why:<br> When you build a single-page app, the bundler (Webpack, Vite, Rollup, whatever) takes <strong>all your JavaScript</strong> — every route, every component, every dependency — and glues it together into one big entry file. That file is loaded on the very first visit, before your user even sees the homepage.</p><p>It doesn’t matter if 90% of your code is for pages the user will never open — it’s all there, clogging up the main thread on day one.</p><p>A few classic ways SPAs end up with monster bundles:</p><ul><li>Importing huge libraries (date pickers, charts, UI frameworks) right in the entry file.</li><li>Loading every route’s code upfront instead of splitting it.</li><li>Shipping all polyfills to all users, even if they don’t need them.</li><li>Dropping images, JSON files, or icons directly inside the JS bundle.</li></ul><h3>Section 3 — How to Fix It: Let’s Analyze an Example Bundle with vite-bundle-analyzer</h3><p>To make this concrete, let’s take a real example app and analyze its bundle using <strong>vite-bundle-analyzer</strong>. This tool visualizes your final build, showing which files and dependencies take up the most space.</p><p>Our app uses a modular architecture and already lazy-loads each module. Yet, as you’ll see in the analyzer output, the main entry file is still surprisingly large:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdSjbeNAWEXyqH_mGngKvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*ffFU716nBbm_kimD0Uaqyw.png" /></figure><p>Just because your app uses lazy loading and a modular architecture doesn’t automatically mean it loads fast.</p><p>In smaller apps, lazy loading modules can significantly reduce the initial bundle size and speed up load times. But in large, complex applications, this isn’t always enough.</p><p>Even if modules are loaded on demand, the main entry chunk can still be bloated with shared dependencies, polyfills, or common code that every module needs. This chunk has to load before anything else, creating a bottleneck.</p><p>So, lazy loading modules is only part of the solution. To truly speed up your app, you need to dig deeper into what’s actually in your main bundle and optimize it aggressively.</p><p>As you can see, our main file is <strong>6.6 MB</strong>, and the useExportData module alone weighs <strong>1.4 MB</strong>. These sizes are definitely too large and need to be trimmed down.</p><p>By analyzing the bundle, we discovered several major issues:</p><ul><li>The <strong>Formio</strong> library for Form management is fully embedded in the main file.</li><li>The <strong>Chakra UI</strong> library is imported multiple times, causing unnecessary duplication.</li><li>The entire <strong>Lodash</strong> library is imported instead of just the parts we actually use.</li><li>All the <strong>icons</strong> are imported right at the start of the app, even if many aren’t needed immediately.</li><li>The <strong>xlsx</strong> library for exporting data is imported upfront but isn’t always used.</li></ul><p>These unnecessary inclusions are inflating our bundle size and slowing down the initial load time.</p><p>-A lot of people assume that writing this code:</p><pre>import { cloneDeep } from &#39;lodash&#39;</pre><p>will import only the cloneDeep function. But in reality, it often imports the entire lodash library.</p><p>Why? Because <strong>tree shaking</strong> — the process that removes unused code — only works fully with <strong>ES6 modules</strong> (import/export). Unfortunately, the main lodash package is built with CommonJS, which many bundlers can’t shake effectively.</p><p>The better approach is to import directly from the specific lodash submodule:</p><pre>import cloneDeep from &#39;lodash/cloneDeep&#39;</pre><p>This way, only the code for cloneDeep is included, keeping your bundle size smaller.</p><p>-Another powerful way to reduce your initial bundle size is to use <strong>dynamic imports</strong> (also called async imports).</p><p>Instead of importing everything upfront, you load libraries or modules <strong>only when they’re actually needed</strong> — which creates separate chunks that the browser downloads on demand.</p><p>For example, instead of this eager import:</p><pre>import jsPDF from &#39;jspdf&#39;<br>import autoTable from &#39;jspdf-autotable&#39;</pre><p>you can do:</p><pre>const jsPDF = (await import(&#39;jspdf&#39;)).default<br>const autoTable = (await import(&#39;jspdf-autotable&#39;)).default</pre><p>This way, these libraries are loaded only when your code reaches that point — often after the initial load.</p><p>The same applies to assets like icons. Rather than bundling all icons at start, you can defer their loading:</p><pre>const iconsList = (await import(&#39;../../assets/icons/selection.json&#39;)).default.icons</pre><p>This approach shrinks your initial JavaScript payload and speeds up the time until your app becomes interactive.</p><p>-As we saw earlier, <strong>Chakra UI</strong> was imported multiple times across different packages, causing duplication in our bundles.</p><p>To fix this, we can tweak Vite’s build configuration to create a <strong>separate chunk</strong> that includes all Chakra UI dependencies (including related libraries like Framer Motion and Emotion). This way, the chunk is shared across all packages that use Chakra UI, preventing redundant code from being included multiple times.</p><p>Here’s how to do it with Vite’s rollupOptions:</p><pre>rollupOptions: {<br>  output: {<br>    manualChunks: {<br>      chakraui: [<br>        &#39;@chakra-ui/react&#39;,<br>        &#39;@emotion/react&#39;,<br>        &#39;@emotion/styled&#39;,<br>        &#39;framer-motion&#39;,<br>      ],<br>    },<br>  },<br>},</pre><p>By bundling these dependencies into a single shared chunk named chakraui, your app loads that code once, reducing overall bundle size and improving caching efficiency.</p><p>-In our app, the <strong>Formio</strong> library ended up embedded inside the main entry bundle — and the root cause was a tricky issue with <strong>circular dependencies</strong> in our code.</p><p>During the build, Rollup warned us about a circular dependency involving modules like:</p><blockquote>Export “TaskContainer” of module “src/components/process/task-container.tsx” was reexported through module “src/components/process/index.tsx” while both modules are dependencies of each other and will end up in different chunks by current Rollup settings.</blockquote><p>This means that two modules depend on each other and are reexported in a way that confuses Rollup’s chunk splitting. Because Rollup can’t safely separate these interdependent modules, it bundles them together in the main chunk.</p><p>Since <strong>Formio</strong> was imported inside one of these circularly linked modules, it got dragged into the main bundle — causing a big chunk of code to load upfront and slowing down our initial load time.</p><p>Fixing circular dependencies is critical to letting Rollup split your code properly and keep heavy libraries like Formio out of your initial bundle.</p><h3>Final Results — What We Achieved</h3><p>After applying these optimizations — fixing imports, using dynamic imports, configuring manual chunks, and resolving circular dependencies — our bundle size shrank dramatically.</p><ul><li>The main entry file went down from <strong>6.6 MB to around 1.06 MB</strong>.</li><li>Modules like useExportData dropped from <strong>1.4 MB to under 200 KB</strong>.</li><li>Heavy libraries like <strong>Chakra UI</strong> were moved into their own shared chunks, loaded only when needed, while <strong>Formio</strong> was isolated and moved solely into the module where it’s used — in this case, the <strong>TaskContainer</strong> component.</li><li>Icons and large assets no longer block the initial load thanks to deferred loading.</li><li>Overall, our app’s <strong>Time to Interactive (TTI)</strong> and <strong>Largest Contentful Paint (LCP)</strong> improved significantly.</li></ul><p>Here’s a before-and-after bundle analyzer screenshot to give you a visual sense of the difference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcmV2RgxsMlyM-mJ4YSuZw.png" /></figure><p>These changes not only sped up the initial load but also made the app feel more responsive and scalable as it grows.</p><h3>Conclusion</h3><p>Optimizing the initial bundle size is one of the most effective ways to speed up your SPA’s load time and improve user experience.</p><p>As we saw, even apps with modular architectures and lazy loading can suffer from unexpectedly large entry chunks caused by import patterns, duplicated dependencies, circular references, and unused assets.</p><p>By carefully analyzing your bundle with tools like <strong>vite-bundle-analyzer</strong>, adopting selective imports, leveraging dynamic imports, and configuring manual chunking, you can dramatically reduce your initial payload.</p><p>The result is faster <strong>Time to Interactive</strong>, better Core Web Vitals scores, and a smoother experience for your users — especially on slower networks and devices.</p><p>Taking the time to identify and fix these issues early will pay off as your app scales, making it leaner, faster, and more maintainable.</p><p>✨ Written by Ayoub Sayah — Frontend Developer</p><p>🔗 <a href="https://www.linkedin.com/in/ayoubsayah">LinkedIn </a>| 💻 <a href="https://github.com/ayoubsayah">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3db155d5c6b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Feature Catalog with Storybook And MSW]]></title>
            <link>https://medium.com/@sayahayoub9827/building-a-feature-catalog-with-storybook-and-msw-f9edd24324c3?source=rss-3d2951eacd9e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9edd24324c3</guid>
            <category><![CDATA[mock-service-worker]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-storybook]]></category>
            <category><![CDATA[msw]]></category>
            <dc:creator><![CDATA[Sayahayoub]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 14:57:41 GMT</pubDate>
            <atom:updated>2025-08-04T15:10:43.958Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern frontend development, working independently from the backend is not just a luxury — it’s a necessity. But beyond that, it’s also about bridging the gap between <strong>developers, QA engineers, and business analysts</strong>.</p><p>A well-structured feature catalog becomes the single source of truth where <strong>user stories, UI behavior, and system interactions</strong> meet. Whether you’re a QA validating functionality, a BA reviewing business flows, or a new team member trying to understand the app, having access to <strong>live, interactive, and documented UI features</strong> saves time and removes ambiguity.</p><p>In this article, I’ll show how I use <strong>Storybook</strong>, <strong>Mock Service Worker (MSW)</strong>, and <strong>Storybook’s </strong><strong>play() function</strong> to build and test features in isolation, using a <strong>Test-Driven Development (TDD)</strong> approach — all without needing a live backend. This method doesn’t just help developers move faster — it fosters <strong>cross-functional collaboration and clarity</strong> throughout the entire product lifecycle.</p><h3>🔧 Setting Up Storybook</h3><p>If you’re new to Storybook, it’s a tool for developing UI components in isolation. It creates a dedicated environment where you can render and test components without launching the full application.</p><p>Install it with:</p><pre>npx storybook@latest init</pre><p>Choose your framework (React, Vue, Angular, etc.) and follow the setup wizard. Once you run it, Storybook will open in your browser on <a href="http://localhost:6006.">http://localhost:6006.</a></p><h3>🧪 Component Documentation and Testing</h3><p>Storybook isn’t just for building UI components in isolation — it also shines when it comes to <strong>documenting and testing</strong> them.</p><p>Each component story serves as a live, interactive use case. This doubles as both <strong>documentation</strong> for your team and a <strong>specification</strong> for behavior. Thanks to tools like <strong>Storybook Autodocs</strong>, documentation can even be <strong>generated automatically</strong> from your stories and metadata — no extra effort required.</p><p>Beyond documentation, Storybook supports <strong>component-level testing</strong> through tools like the play function and Test Runner. You can simulate interactions, verify behavior, and even catch regressions early, all within your Storybook environment.</p><h3>♿ Accessibility (a11y) with Storybook</h3><p>Accessibility is often overlooked — but Storybook makes it easy to <strong>catch accessibility issues early</strong> in development.</p><p>By using the @storybook/addon-a11y, you get automatic warnings for:</p><ul><li>Missing aria labels</li><li>Poor color contrast</li><li>Inaccessible roles</li><li>Keyboard navigation issues</li></ul><h3>🧱 What Do We Mean by “Feature”?</h3><p>In our application, a <em>feature</em> represents a <strong>self-contained module</strong> — like <strong>Authentication</strong>, <strong>Dashboard</strong>, <strong>User Management</strong>, etc. Each feature may consist of multiple components, API integrations, and UI states.</p><p>We use Storybook as a <strong>living feature catalog</strong> — documenting and testing each module in its various states: loading, success, error, edge cases, etc</p><h3>🔧 Getting Started: Storybook + MSW</h3><p>We use Storybook to build components, and MSW (Mock Service Worker) to <strong>simulate API responses</strong> — allowing us to work without a real backend.</p><h4>What is a Service Worker?</h4><p>A <strong>Service Worker</strong> is a background script that runs independently of the web page. It can intercept and handle network requests, enabling features like offline support, caching, and request mocking.</p><h4><strong>MSW (Mock Service Worker)</strong></h4><p>In the browser, <strong>MSW (Mock Service Worker)</strong> works by registering a <strong>Service Worker</strong>, a browser feature designed to intercept and handle network requests. When active, the MSW Service Worker:</p><ol><li><strong>Intercepts outgoing HTTP requests</strong> (like fetch, XMLHttpRequest) made by your application or component.</li><li><strong>Matches them</strong> against the mock handlers you define (based on URL, method, etc.).</li><li><strong>Responds with mock data</strong> instead of letting the request go to a real server.</li></ol><p>Because this happens <strong>at the network level</strong>, your frontend code behaves as if it’s talking to a real API. This makes it ideal for Storybook: you can develop and test features in complete isolation — including error cases, delays, or different user roles — all without a running backend.</p><h4>Install MSW and the addon</h4><pre>npm i msw msw-storybook-addon -D</pre><h4>Generate service worker for MSW in your public folder.</h4><pre>npx msw init public/</pre><h4>Configure the addon</h4><p>Enable MSW in Storybook by initializing MSW and providing the MSW loader in ./storybook/preview.js: by initializing MSW and providing the MSW loader in ./storybook/preview.js:</p><pre>import { initialize, mswLoader } from &#39;msw-storybook-addon&#39;<br><br>// Initialize MSW<br>initialize()<br><br>const preview = {<br>  parameters: {<br>    // your other code...<br>  },<br>  // Provide the MSW addon loader globally<br>  loaders: [mswLoader],<br>}<br><br>export default preview</pre><h3>What is loaders in Storybook?</h3><p>In Storybook, loaders are <strong>asynchronous functions</strong> that run <strong>before your story renders</strong>. They allow you to <strong>set up external data or mocking logic</strong> needed by your components.</p><p>Each loader can:</p><ul><li>Fetch data,</li><li>Initialize state,</li><li>Set up mocks (like MSW),</li><li>Or prepare any environment your component needs.</li></ul><p>These loaders run once per story (or globally if added in preview.js/ts like in your case).</p><h3>What does mswLoader do?</h3><p>mswLoader is provided by msw-storybook-addon. When used in loaders, it:</p><ul><li><strong>Registers the appropriate request handlers</strong> defined in your story (parameters.msw) or globally,</li><li>Ensures <strong>MSW is ready</strong> before the component renders,</li><li>Allows <strong>each story to define its own mock API behavior</strong>.</li></ul><p>This way, every Storybook story can run in isolation with <strong>custom API responses</strong> simulated through MSW</p><pre>export const ValidExcel: AddUsersBulkType = {<br>  render,<br>  parameters: {<br>    msw: {<br>      handlers: [<br>        http.post(&#39;user/bulk&#39;, async () =&gt; {<br>          await delay(1000)<br>          return HttpResponse.json(SuccessData)<br>        }),<br>      ],<br>    },<br>  },<br>}<br><br>export const InvalidExcel: AddUsersBulkType = {<br>  render,<br>  parameters: {<br>    msw: {<br>      handlers: [<br>        http.post(&#39;user/bulk&#39;, async () =&gt; {<br>          await delay(1000)<br>          return HttpResponse.json(ErrorData)<br>        }),<br>      ],<br>    },<br>  },<br>}</pre><p>This code defines two Storybook stories that use <strong>Mock Service Worker (MSW)</strong> to simulate different API responses for the same endpoint (user/bulk). Each story configures its own msw.handlers using the parameters property, allowing Storybook to mock network requests directly in the browser.</p><p>This setup is useful for testing different scenarios — for example, one story returns a <strong>successful</strong> API response, while the other simulates a <strong>failure</strong>. By mocking both success and error cases, developers can validate how the component behaves under various conditions, all without relying on a real backend.</p><p>This diagram illustrates the workflow and interactions between the involved parties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqMQCGv1ZYKb240tMUcD3A.png" /></figure><h3>🤖 Automating Interactions with play()</h3><pre>  play: async ({ canvasElement, args, step }) =&gt; {<br>    const canvas = within(canvasElement)<br>    await step(&#39;submit-without-upload&#39;, async () =&gt; {<br>      const button = canvas.getByText(&#39;Next&#39;)<br>      button.click()<br><br>      await waitFor(async () =&gt; {<br>        expect(canvas.getByText(&#39;File is Required&#39;)).toBeVisible()<br>      })<br>    })<br>    const input = (await canvas.getByTestId(&#39;uplaod-document&#39;)) as HTMLInputElement<br>    const data = [<br>      [&#39;Name&#39;, &#39;Age&#39;],<br>      [&#39;John&#39;, 30],<br>      [&#39;Alice&#39;, 25],<br>      [&#39;Bob&#39;, 35],<br>    ]<br>    const write = (await import(`xlsx-js-style`)).write<br>    const utils = (await import(`xlsx-js-style`)).utils<br><br>    const wb = utils.book_new()<br><br>    const ws = utils.aoa_to_sheet(data)<br><br>    utils.book_append_sheet(wb, ws, &#39;Sheet1&#39;)<br><br>    const blob = new Blob([write(wb, { type: &#39;array&#39;, bookType: &#39;xlsx&#39; })], { type: &#39;application/octet-stream&#39; })<br><br>    const file = new File([blob], &#39;dummy.xlsx&#39;, {<br>      type: &#39;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&#39;,<br>    })<br>    await step(&#39;upload-documents&#39;, async () =&gt; {<br>      await waitFor(() =&gt;<br>        fireEvent.change(input, {<br>          target: { files: [file] },<br>        })<br>      )<br><br>      await waitFor(async () =&gt; {<br>        expect(input.files &amp;&amp; input.files.length).toBe(1)<br>      })<br>    })<br><br>    await step(&#39;submit-form&#39;, async () =&gt; {<br>      const button = canvas.getByText(&#39;Next&#39;)<br>      setTimeout(() =&gt; {<br>        button.click()<br>      }, 2000)<br>    })<br>  },</pre><p>This interaction test verifies the complete flow of:</p><ul><li>Submitting an empty form and checking for a validation error.</li><li>Uploading a valid Excel file.</li><li>Submitting the form successfully afterward.</li></ul><p>It ensures the UI responds correctly to user actions, covering both edge case (no file) and valid scenario (valid file).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8oi2o8EVywGEVhSg-NJng.gif" /></figure><p>This documentation section acts as a <strong>feature catalog</strong>, centralizing key information about the functionality implemented in this component. It is intended to:</p><ul><li><strong>Explain the purpose</strong> and <strong>business value</strong> of the feature.</li><li>Provide a <strong>clear user story</strong> and flow.</li><li>Help <strong>QA</strong>, <strong>BA</strong>, and <strong>new team members</strong> quickly understand expected behavior.</li><li>Serve as a <strong>reference point</strong> during testing, validation, and onboarding.</li></ul><p>All interactive steps and edge cases are demonstrated in stories and supported by relevant visuals or test cases when needed.</p><h3>✅ Conclusion</h3><p>By integrating <strong>Storybook</strong> with <strong>MSW</strong>, we create more than just a development tool — we build a <strong>living, collaborative feature catalog</strong> that supports both <strong>technical and non-technical stakeholders</strong>.</p><ul><li><strong>Developers</strong> benefit from working in isolation, testing edge cases early, and developing with confidence.</li><li><strong>QA teams</strong> can simulate various user scenarios, validate behaviors directly in Storybook, and ensure each user story is fully covered.</li><li><strong>Business Analysts (BAs)</strong> — especially new joiners — can quickly explore features, understand expected flows, and align them with business requirements.</li></ul><p>With stories acting as <strong>live specifications</strong> and play() interactions automating user flows, the entire team gains a shared understanding of the product. This approach <strong>accelerates onboarding, simplifies validation, and strengthens communication</strong> across departments — all while improving the quality and reliability of the application.</p><p>✨ Written by Ayoub Sayah — Frontend Developer</p><p>🔗 <a href="https://www.linkedin.com/in/ayoubsayah">LinkedIn </a>| 💻 <a href="https://github.com/ayoubsayah">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9edd24324c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>