<?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 Arpan Sahoo on Medium]]></title>
        <description><![CDATA[Stories by Arpan Sahoo on Medium]]></description>
        <link>https://medium.com/@sahoo.arpan7?source=rss-868e2225134e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_DyNveXcuZMVZjLL.</url>
            <title>Stories by Arpan Sahoo on Medium</title>
            <link>https://medium.com/@sahoo.arpan7?source=rss-868e2225134e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:04:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sahoo.arpan7/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[Reflow vs Repaint: The Performance Story Every Frontend Engineer Eventually Learns]]></title>
            <link>https://medium.com/@sahoo.arpan7/reflow-vs-repaint-the-performance-story-every-frontend-engineer-eventually-learns-21400aa5d4f1?source=rss-868e2225134e------2</link>
            <guid isPermaLink="false">https://medium.com/p/21400aa5d4f1</guid>
            <dc:creator><![CDATA[Arpan Sahoo]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 17:47:40 GMT</pubDate>
            <atom:updated>2026-01-18T17:55:01.089Z</atom:updated>
            <content:encoded><![CDATA[<p>I used to think frontend performance problems were obvious.</p><p>A slow API.<br> A large bundle.<br> Too much JavaScript.</p><p>Then a UI animation — barely noticeable — made scrolling feel… <em>off</em>.</p><p>Not broken.<br> Not frozen.<br> Just uncomfortable.</p><p>Chrome DevTools showed the real culprit:</p><blockquote><strong><em>Layout → Paint → Layout → Paint → Layout…</em></strong></blockquote><p>That was my real introduction to <strong>reflow and repaint</strong> — not as interview buzzwords, but as production pain.</p><h3>The Browser Has a Pipeline (And It Always Wins)</h3><p>We build in components and hooks.</p><p>Browsers don’t.</p><p>Browsers work in a <strong>rendering pipeline</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/0*Col9rHLorR6pu68_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*SVooI-UY6-7t05tm" /></figure><ol><li>DOM &amp; CSSOM</li><li>Render Tree</li><li><strong>Layout (Reflow)</strong> — placement &amp; measurement</li><li><strong>Paint (Repaint)</strong> — coloring pixels</li><li>Composite — layers + GPU</li></ol><p>Once I internalized this pipeline, a lot of “random jank” stopped being random.</p><h3>Reflow: When the Browser Recalculates Reality</h3><p><strong>Reflow (Layout)</strong> is when the browser figures out:</p><ul><li>Where elements go</li><li>How big they are</li><li>How they affect each other</li></ul><p>In short:</p><blockquote><strong><em>Reflow is geometry</em></strong></blockquote><p>Change the width of one element, and the browser may need to recalculate:</p><ul><li>Its children</li><li>Its siblings</li><li>Sometimes its parents</li></ul><p>That’s why:</p><blockquote><strong><em>Reflow has a high performance impact</em></strong></blockquote><h3>What Actually Triggers Reflow</h3><ul><li>Adding or removing DOM elements</li><li>Changing dimensions (width, height, padding, margin)</li><li>Changing font size or text</li><li>Window resize</li><li>Reading layout values:</li><li>offsetHeight</li><li>clientWidth</li><li>getBoundingClientRect()</li><li>Changing display: none</li><li>Modifying DOM structure</li></ul><p>The most dangerous pattern?</p><blockquote><strong><em>Reading layout after writing styles</em></strong></blockquote><p>This forces <strong>synchronous reflow</strong> — also known as <em>layout thrashing</em>.</p><h3>Repaint: When Only the Pixels Change</h3><p><strong>Repaint</strong> is cheaper.</p><p>No geometry recalculation.<br> No element movement.</p><p>Just:</p><blockquote><em>“What color should this pixel be now?”</em></blockquote><p>Triggers include:</p><ul><li>Color changes</li><li>Background updates</li><li>Opacity</li><li>Box-shadow</li><li>Outline</li><li>visibility: hidden</li></ul><p>That’s why:</p><ul><li>visibility: hidden → repaint</li><li>display: none → <strong>reflow + repaint</strong></li></ul><h3>The Rule That Changed How I Design UI</h3><p>After enough profiling sessions, one rule stuck:</p><blockquote><strong><em>Avoid layout changes during interaction paths</em></strong></blockquote><p>Scrolling.<br> Typing.<br> Dragging.<br> Animating.</p><p>If it happens frequently, <strong>don’t touch layout</strong>.</p><h3>Then React 18 Changed the Conversation</h3><p>Before React 18, rendering was synchronous.</p><p>Once started:</p><ul><li>Main thread blocked</li><li>Scroll waited</li><li>Layout recalculated immediately</li></ul><p>React 18 introduced <strong>Concurrent Rendering</strong>, built on one simple idea:</p><blockquote><strong><em>Not all renders are equally urgent</em></strong></blockquote><p>React can now:</p><ul><li>Pause rendering</li><li>Resume later</li><li>Drop low-priority renders</li></ul><p>This matters because it controls <strong>when reflow and repaint happen</strong>.</p><h3>Real Scroll + Concurrent Rendering Case Studies</h3><h3>Case 1: Infinite Scroll That Felt “Almost Smooth”</h3><p>Problem:</p><ul><li>Items appended during scroll</li><li>Layout recalculated mid-scroll</li><li>Paint cycles stacked</li></ul><p>Fix:</p><ul><li>IntersectionObserver</li><li>startTransition for non-urgent updates</li></ul><pre>observer.onIntersect(() =&gt; {<br>  startTransition(() =&gt; {<br>    setItems(prev =&gt; [...prev, ...nextPage]);<br>  });<br>});</pre><p><strong>Why it worked</strong></p><ul><li>Scroll stayed high priority</li><li>Rendering became interruptible</li><li>Reflow deferred until safe</li></ul><h3>Case 2: Search-as-You-Type Lag</h3><p>Problem:</p><ul><li>Every keystroke re-rendered a large table</li><li>Layout recalculated repeatedly</li></ul><p>Fix:</p><pre>setInputValue(value); // urgent</pre><pre>startTransition(() =&gt; {<br>  setFilteredData(filter(data, value)); // can wait<br>});</pre><p>Typing stayed instant.<br> Layout pressure dropped dramatically.</p><h3>IntersectionObserver: Stop Polling, Start Listening</h3><p>Old approach:</p><pre>window.addEventListener(&#39;scroll&#39;, handler);</pre><p>Problem:</p><ul><li>Scroll listeners trigger layout reads</li><li>Reflow pressure during interaction</li></ul><p><strong>IntersectionObserver</strong> flips the model:</p><blockquote><em>“Tell me when it becomes visible.”</em></blockquote><p>Why it matters:</p><ul><li>Browser batches calculations</li><li>No forced reflow</li><li>Perfect for scroll-heavy UIs</li></ul><p>Use cases:</p><ul><li>Lazy loading</li><li>Infinite scroll</li><li>Scroll-based animations</li><li>Analytics impressions</li></ul><h3>MutationObserver: Observe Without Touching Layout</h3><p>Sometimes you don’t care <em>where</em> something is.</p><p>You care <em>that it changed</em>.</p><p>MutationObserver lets you react to:</p><ul><li>DOM insertions</li><li>Attribute changes</li><li>Text updates</li></ul><p>No layout reads.<br> Minimal repaint cost.</p><p>Ideal for:</p><ul><li>CMS-driven content</li><li>Third-party scripts</li><li>Design-system slots</li></ul><h3>requestAnimationFrame: The Final Handshake</h3><p>Even with modern APIs, requestAnimationFrame still matters.</p><p>It schedules updates <strong>right before paint</strong>:</p><pre>requestAnimationFrame(() =&gt; {<br>  element.style.transform = &#39;translateX(100px)&#39;;<br>});</pre><p>I think of rAF as:</p><blockquote><strong><em>The boundary between JavaScript intent and visual reality</em></strong></blockquote><h3>CSS Best Practices to Minimize Reflow &amp; Repaint</h3><h3>Prefer Transform &amp; Opacity</h3><pre>/* ❌ Bad */<br>left: 100px;</pre><pre>/* ✅ Good */<br>transform: translateX(100px);</pre><p>✔ No reflow<br> ✔ GPU accelerated<br> ✔ Smooth animations</p><h3>Avoid Animating Layout Properties</h3><p>Avoid:</p><ul><li>width</li><li>height</li><li>top</li><li>left</li><li>margin</li></ul><p>These trigger reflow on every frame.</p><h3>Avoid Table-Based Layouts</h3><p>Tables can trigger <strong>global reflow</strong>.<br> Prefer:</p><ul><li>Flexbox</li><li>CSS Grid</li></ul><h3>JavaScript Best Practices</h3><h3>Batch DOM Changes</h3><pre>// ❌ Multiple writes<br>el.style.width = &#39;100px&#39;;<br>el.style.height = &#39;200px&#39;;</pre><pre>// ✅ One class<br>el.classList.add(&#39;expanded&#39;);</pre><h3>Avoid Layout Thrashing</h3><pre>// ❌ Forces reflow<br>el.style.width = el.offsetWidth + &#39;px&#39;;</pre><p>Instead:</p><pre>const width = el.offsetWidth;<br>requestAnimationFrame(() =&gt; {<br>  el.style.width = width + &#39;px&#39;;<br>});</pre><h3>Detach Before Heavy Updates</h3><pre>el.style.display = &#39;none&#39;;<br>// batch changes<br>el.style.display = &#39;block&#39;;</pre><h3>React Best Practices</h3><h3>Separate Urgent vs Non-Urgent State</h3><ul><li>Input, scroll → urgent</li><li>Filtering, rendering large lists → non-urgent</li></ul><p>Use startTransition.</p><h3>Avoid JS-driven Animations</h3><p>Prefer:</p><ul><li>CSS transitions</li><li>Transform-based animations</li></ul><p>Avoid:</p><ul><li>setState inside animation loops</li></ul><h3>Memoization Matters</h3><p>Use:</p><ul><li>React.memo</li><li>useMemo</li><li>useCallback</li></ul><p>To prevent unnecessary re-renders → fewer layout recalculations.</p><h3>Virtualize Large Lists</h3><p>Rendering fewer DOM nodes means:</p><ul><li>Less layout</li><li>Less paint</li><li>Better scroll performance</li></ul><h3>Final Takeaway</h3><p>Reflow taught me <strong>what hurts the browser</strong>.<br> Repaint taught me <strong>what’s cheaper to change</strong>.<br> Concurrent rendering taught me <strong>what can wait</strong>.</p><p>Modern frontend performance isn’t about tricks.</p><p>It’s about <strong>coordination</strong>:<br> between CSS,<br> JavaScript,<br> React,<br> and the browser’s rendering engine.</p><p>Once you respect that relationship,<br> smooth UI stops being accidental — <br> and starts being intentional.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21400aa5d4f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shift-Left Accessibility: Catching WCAG Violations at Unit Test Level]]></title>
            <link>https://medium.com/@sahoo.arpan7/shift-left-accessibility-catching-wcag-violations-at-unit-test-level-b2470101605a?source=rss-868e2225134e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2470101605a</guid>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[wcag]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Arpan Sahoo]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 18:31:13 GMT</pubDate>
            <atom:updated>2026-01-14T04:54:23.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Accesibility" src="https://cdn-images-1.medium.com/max/1024/0*06FfETkH03WDTWeH.jpg" /></figure><p>Most accessibility bugs don’t exist because teams are careless.</p><p>They exist because accessibility is treated as a <strong>final checkpoint</strong>:</p><ul><li>A Lighthouse audit before release</li><li>A manual screen-reader test in QA</li><li>A compliance ticket after production</li></ul><p>By then, fixing accessibility isn’t a refactor — it’s a redesign.</p><p>The truth is simple:</p><blockquote><strong><em>If accessibility isn’t tested early, it ships broken.</em></strong></blockquote><p>The most effective accessibility strategy today is not better audits — <br> it’s <strong>shifting accessibility left</strong>, all the way to <strong>unit tests</strong>.</p><h3>Why Accessibility Bugs Keep Shipping</h3><p>Roughly <strong>15% of the global population</strong> relies on assistive technologies.</p><p>Yet many production apps still ship with:</p><ul><li>Inputs without labels</li><li>Clickable divs pretending to be buttons</li><li>Icon-only controls with no meaning</li><li>Broken keyboard navigation</li></ul><p>Not because developers don’t care — <br> but because <strong>their tests don’t fail when accessibility breaks</strong>.</p><p>When tests only validate DOM structure, accessibility regressions slip through silently.</p><h3>What “Shift-Left Accessibility” Actually Means</h3><p>Shifting left means moving accessibility checks:</p><ul><li>❌ Away from audits</li><li>❌ Away from production</li><li>❌ Away from manual QA</li></ul><p>➡️ <strong>Into component design and unit tests</strong></p><p>So instead of asking:</p><blockquote><em>“Does this component render?”</em></blockquote><p>We ask:</p><blockquote><em>“Can a real user interact with this component?”</em></blockquote><p>That single change reshapes how we write tests — and how accessible our apps become.</p><h3>Why Traditional Unit Tests Miss Accessibility Issues</h3><p>A typical React test looks like this:</p><pre>screen.getByTestId(&quot;submit-btn&quot;);<br>fireEvent.click(button);</pre><p>This test passes even if:</p><ul><li>The button isn’t keyboard accessible</li><li>Screen readers don’t recognize it</li><li>The element is visually disabled but still clickable</li></ul><p>The test passes — <strong>but the user fails</strong>.</p><p>Accessibility-aware tests don’t lie.</p><h3>Real-World Failure #1: Clickable div Instead of button</h3><h3>❌ Inaccessible Component</h3><pre>&lt;div onClick={onSubmit}&gt;Submit&lt;/div&gt;</pre><h3>What Breaks</h3><ul><li>Not keyboard focusable</li><li>No semantic role</li><li>Screen readers don’t announce intent</li></ul><h3>WCAG Violations</h3><ul><li><strong>2.1.1 Keyboard</strong></li><li><strong>4.1.2 Name, Role, Value</strong></li><li><strong>1.3.1 Info and Relationships</strong></li></ul><h3>✅ Accessibility-Aware Test</h3><pre>screen.getByRole(&quot;button&quot;, { name: /submit/i });</pre><p>The test fails immediately — exactly what we want.</p><h3>✅ Correct Fix</h3><pre>&lt;button onClick={onSubmit}&gt;Submit&lt;/button&gt;</pre><h3>Real-World Failure #2: Label Not Bound to Input</h3><h3>❌ Inaccessible Component</h3><pre>&lt;label&gt;Email&lt;/label&gt;<br>&lt;input type=&quot;email&quot; /&gt;</pre><h3>What Breaks</h3><ul><li>Screen readers can’t associate label</li><li>Voice navigation fails</li><li>Form context is lost</li></ul><h3>WCAG Violations</h3><ul><li><strong>1.3.1 Info and Relationships</strong></li><li><strong>3.3.2 Labels or Instructions</strong></li></ul><h3>✅ Accessibility-Aware Test</h3><pre>screen.getByLabelText(/email/i);</pre><h3>✅ Correct Fix</h3><pre>&lt;label htmlFor=&quot;email&quot;&gt;Email&lt;/label&gt;<br>&lt;input id=&quot;email&quot; type=&quot;email&quot; /&gt;</pre><h3>Real-World Failure #3: Missing alt Text on Images</h3><h3>❌ Inaccessible Component</h3><pre>&lt;img src=&quot;/profile.png&quot; /&gt;</pre><h3>What Breaks</h3><ul><li>Screen readers announce “image”</li><li>No alternative content exists</li></ul><h3>WCAG Violation</h3><ul><li><strong>1.1.1 Non-Text Content</strong></li></ul><h3>✅ Automated Accessibility Test</h3><pre>import { axe } from &quot;jest-axe&quot;;</pre><pre>const { container } = render(&lt;Profile /&gt;);<br>expect(await axe(container)).toHaveNoViolations();</pre><h3>✅ Correct Fix</h3><pre>&lt;img src=&quot;/profile.png&quot; alt=&quot;User profile picture&quot; /&gt;</pre><h3>Real-World Failure #4: Visually Disabled but Functionally Clickable</h3><h3>❌ Inaccessible Component</h3><pre>&lt;button style={{ pointerEvents: &quot;none&quot; }}&gt;<br>  Save<br>&lt;/button&gt;</pre><h3>What Breaks</h3><ul><li>Screen readers still announce it as interactive</li><li>Keyboard behavior is inconsistent</li></ul><h3>WCAG Violations</h3><ul><li><strong>4.1.2 Name, Role, Value</strong></li><li><strong>2.1.1 Keyboard</strong></li></ul><h3>❌ Lying Test</h3><pre>fireEvent.click(button);</pre><h3>✅ Realistic Test</h3><pre>await userEvent.click(<br>  screen.getByRole(&quot;button&quot;, { name: /save/i })<br>);</pre><h3>✅ Correct Fix</h3><pre>&lt;button disabled&gt;Save&lt;/button&gt;</pre><h3>Real-World Failure #5: Icon-Only Button Without Accessible Name</h3><h3>❌ Inaccessible Component</h3><pre>&lt;button&gt;<br>  &lt;CloseIcon /&gt;<br>&lt;/button&gt;</pre><h3>What Breaks</h3><ul><li>Screen readers announce “button”</li><li>No purpose is communicated</li></ul><h3>WCAG Violations</h3><ul><li><strong>4.1.2 Name, Role, Value</strong></li><li><strong>2.4.6 Headings and Labels</strong></li></ul><h3>✅ Accessibility-Aware Test</h3><pre>screen.getByRole(&quot;button&quot;, { name: /close/i });</pre><h3>✅ Correct Fix</h3><pre>&lt;button aria-label=&quot;Close&quot;&gt;<br>  &lt;CloseIcon /&gt;<br>&lt;/button&gt;</pre><h3>Real-World Failure #6: Keyboard Trap in a Modal</h3><h3>What Breaks</h3><ul><li>Focus enters modal</li><li>User cannot escape using keyboard</li></ul><h3>WCAG Violations</h3><ul><li><strong>2.1.2 No Keyboard Trap</strong></li><li><strong>2.4.3 Focus Order</strong></li></ul><h3>✅ Focus Test</h3><pre>await userEvent.tab();<br>expect(closeButton).toHaveFocus();</pre><h3>WCAG → React Testing Library: The Hidden Superpower</h3><p>You don’t need to memorize WCAG.</p><p>When you test like a user, <strong>WCAG compliance becomes a side effect</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mZLtnqYgPVujnCQLWoXsA.png" /></figure><blockquote><strong><em>If you can’t query it by role or label — it’s probably inaccessible.</em></strong></blockquote><h3>Stop Using data-testid by Default</h3><p>data-testid selectors:</p><ul><li>Don’t enforce semantics</li><li>Don’t fail when accessibility breaks</li><li>Encourage test-only markup</li></ul><p>Use them <strong>only as a last resort</strong>.</p><h3>RTL Query Priority</h3><ol><li>getByRole</li><li>getByLabelText</li><li>getByPlaceholderText</li><li>getByText</li><li>❌ getByTestId</li></ol><h3>Accessibility-First Unit Testing Checklist</h3><ul><li>✅ Use semantic HTML first</li><li>✅ Prefer getByRole and getByLabelText</li><li>✅ Use user-event, not fireEvent</li><li>✅ Run jest-axe on critical components</li><li>✅ Treat accessibility failures as blockers</li></ul><h3>Final Thought</h3><p>Accessibility is not:</p><ul><li>A QA task</li><li>A compliance phase</li><li>A checklist</li></ul><p>Accessibility is a <strong>design constraint</strong>.</p><p>And the best place to enforce constraints is <strong>unit tests</strong>.</p><p>Shift accessibility left.<br> Let your tests protect your users — and your product.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2470101605a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cumulative Layout Shift (CLS): Guide to One of the Most Misunderstood Core Web Vitals]]></title>
            <link>https://medium.com/@sahoo.arpan7/cumulative-layout-shift-cls-guide-to-one-of-the-most-misunderstood-core-web-vitals-5f135c68cb6f?source=rss-868e2225134e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f135c68cb6f</guid>
            <dc:creator><![CDATA[Arpan Sahoo]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 15:30:01 GMT</pubDate>
            <atom:updated>2026-01-10T18:14:03.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cumulative Layout Shift (CLS): The Most Misunderstood Core Web Vital (2026 Guide)</h3><p>Cumulative Layout Shift (CLS) is one of Google’s Core Web Vitals — and also one of the most misunderstood performance metrics.</p><p>Many teams proudly ship green Lighthouse reports, yet users still complain:</p><ul><li>“The page feels jumpy”</li><li>“I keep clicking the wrong button”</li><li>“The UI feels unstable, especially on mobile”</li></ul><p>That disconnect almost always points to <strong>CLS problems in real user conditions</strong>.</p><p>In this guide, we’ll break CLS down from first principles and rebuild it the <em>right way</em> — with <strong>React and Next.js–specific examples</strong>, real production pitfalls, and fixes that actually work.</p><h3>What Is Cumulative Layout Shift (CLS)?</h3><p>CLS measures <strong>unexpected visual movement</strong> of page content during the entire lifespan of a page.</p><p>A layout shift occurs when a visible element changes its position between two rendered frames <strong>without user interaction</strong>.</p><h3>What CLS Measures</h3><ul><li>Sudden movement of text, buttons, images</li><li>Content shifting because something loaded late</li><li>UI jumping during page load <em>or navigation</em></li></ul><h3>What CLS Does NOT Measure</h3><ul><li>Layout changes triggered by <strong>user actions</strong><br> (e.g. clicking a button, opening an accordion)</li></ul><h3>Why CLS Matters</h3><p>CLS is not just a ranking signal — it’s a <strong>trust signal</strong>.</p><p>High CLS leads to:</p><ul><li>Mis-clicks and accidental interactions</li><li>Poor readability</li><li>Higher bounce rates</li><li>Frustrated users (especially on mobile)</li></ul><p>Google’s thresholds:</p><ul><li><strong>Good:</strong> ≤ 0.1</li><li><strong>Needs improvement:</strong> 0.1–0.25</li><li><strong>Poor:</strong> &gt; 0.25</li></ul><h3>How CLS Is Actually Calculated (Session Windows)</h3><p>CLS is <strong>not</strong> a simple sum of all layout shifts.</p><p>Google groups layout shifts into <strong>session windows</strong>:</p><ul><li>A session window starts with a layout shift</li><li>Ends after <strong>1 second of no shifts</strong></li><li>Maximum window length: <strong>5 seconds</strong></li><li>The <strong>largest window score</strong> becomes the CLS value</li></ul><p>This prevents slow, tiny shifts over time from unfairly inflating CLS — and better reflects <strong>human perception</strong>.</p><h3>Lab CLS vs Real-User CLS (Why Lighthouse Lies)</h3><p>One of the biggest CLS traps:</p><blockquote><em>“CLS is green in Lighthouse, so we’re good.”</em></blockquote><p>Not necessarily.</p><h3>Lighthouse (Lab Data)</h3><ul><li>Fast device</li><li>Stable network</li><li>Controlled viewport</li><li>No real-world variability</li></ul><h3>Real Users (Field Data)</h3><ul><li>Slower phones</li><li>Network delays</li><li>Third-party scripts</li><li>Feature flags, ads, consent banners</li></ul><p><strong>Google rankings use real-user data (CrUX), not Lighthouse.</strong></p><h3>Measuring CLS Correctly with the web-vitals Library</h3><p>The most reliable way to measure CLS in production is using the <strong>web-vitals</strong> library.</p><h3>Install</h3><pre>npm install web-vitals</pre><h3>Measure CLS</h3><pre>import { onCLS } from &#39;web-vitals&#39;;</pre><pre>onCLS((metric) =&gt; {<br>  console.log(&#39;CLS:&#39;, metric.value);<br>});</pre><p>This captures:</p><ul><li>Real layout shifts</li><li>Actual user sessions</li><li>Navigation-based CLS (SPAs)</li></ul><p>You can send this data to analytics, logs, or a monitoring system.</p><h3>Core Principle to Eliminate CLS</h3><blockquote><strong><em>Data can be async. Layout must not be.</em></strong></blockquote><p>Most CLS issues come from <strong>missing layout reservations</strong>, not slow loading.</p><h3>1. Images, Media &amp; Iframes: Always Reserve Space</h3><p>Never let images or embeds decide their size at runtime.</p><h3>❌ Bad</h3><pre>&lt;img src=&quot;/banner.jpg&quot; /&gt;</pre><h3>✅ Good</h3><pre>&lt;img src=&quot;/banner.jpg&quot; width=&quot;1200&quot; height=&quot;600&quot; /&gt;</pre><p>Or use CSS:</p><pre>.media {<br>  aspect-ratio: 16 / 9;<br>}</pre><h3>2. The min-height Strategy (Critical for Async Content)</h3><p>Dynamic content is the #1 CLS cause in React apps.</p><h3>Problem</h3><ul><li>API data loads after render</li><li>Component grows in height</li><li>Everything below shifts</li></ul><h3>Solution: Reserve Space</h3><pre>.card {<br>  min-height: 240px;<br>}</pre><p>Skeletons must <strong>match final content height</strong> — otherwise CLS still occurs.</p><h3>3. CLS in React Applications</h3><h3>Common React CLS Causes</h3><ul><li>Conditional rendering based on async data</li><li>Auth-based UI appearing late</li><li>Skeleton mismatch</li><li>Lazy-loaded components without space reservation</li></ul><h3>Example ❌</h3><pre>{data &amp;&amp; &lt;ProductDetails /&gt;}</pre><h3>Example ✅</h3><pre>&lt;div style={{ minHeight: 300 }}&gt;<br>  {data ? &lt;ProductDetails /&gt; : &lt;Skeleton /&gt;}<br>&lt;/div&gt;</pre><h3>4. CLS During SPA Navigation (React &amp; Next.js)</h3><p>CLS is <strong>not just a page-load problem</strong>.</p><p>In SPAs:</p><ul><li>Layout persists across routes</li><li>CLS often happens during navigation</li></ul><h3>Common Issues</h3><ul><li>Header height changes after auth resolves</li><li>Sidebar appears based on permissions</li><li>Route skeleton doesn’t match final page</li></ul><h3>Fix</h3><ul><li>Keep layout containers stable</li><li>Reserve space at layout level</li><li>Match loading.tsx with final layout</li></ul><pre>&lt;Layout&gt;<br>  {isLoading ? &lt;PageSkeleton /&gt; : &lt;Page /&gt;}<br>&lt;/Layout&gt;</pre><h3>5. Next.js-Specific CLS Pitfalls</h3><p>Watch out for:</p><ul><li>Client-only components in layout.tsx</li><li>Dynamic imports without reserved space</li><li>Mismatched loading.tsx</li><li>Font loading issues</li></ul><p><strong>Rule:</strong> Shared layouts must not change height between routes.</p><h3>6. Fonts &amp; CLS: font-display Tradeoffs</h3><p>Fonts are a silent CLS killer.</p><h3>font-display: swap</h3><ul><li>Fast text</li><li>Possible layout shift</li></ul><h3>font-display: optional</h3><ul><li>Layout stability</li><li>Font may never load</li></ul><p>There is <strong>no universal best choice</strong> — choose based on UX priority.</p><p>Reduce CLS by:</p><ul><li>Using similar fallback fonts</li><li>Avoiding late-loading font weights</li><li>Preloading critical fonts</li></ul><h3>7. Animations That Cause CLS</h3><p>Avoid animating layout-affecting properties:</p><ul><li>height</li><li>margin</li><li>top/left</li></ul><p>Prefer:</p><ul><li>transform</li><li>opacity</li></ul><p>These do <strong>not</strong> trigger CLS.</p><h3>Complete CLS Prevention Checklist</h3><h3>Layout &amp; Structure</h3><ul><li>Reserve space for images and media</li><li>Use min-height for async content</li><li>Keep shared layouts stable</li></ul><h3>React &amp; SPA</h3><ul><li>Skeletons match final UI</li><li>No layout changes after navigation</li><li>Auth-based UI space reserved</li></ul><h3>Fonts &amp; Assets</h3><ul><li>Intentional font-display</li><li>Preload critical fonts</li><li>Avoid late-loading weights</li></ul><h3>Monitoring</h3><ul><li>Measure CLS using web-vitals</li><li>Track real-user CLS</li><li>Set CLS budget ≤ 0.1</li></ul><h3>Common CLS Myths (Debunked)</h3><p>❌ CLS only matters on page load<br> ❌ Lighthouse CLS is enough<br> ❌ Skeletons always fix CLS<br> ❌ CLS is a CSS-only problem</p><p><strong>CLS is a rendering + data + layout coordination problem.</strong></p><h3>Final Thoughts</h3><p>Cumulative Layout Shift isn’t about chasing a score.</p><p>It’s about building interfaces that <strong>anticipate change</strong>.</p><p>When layouts reserve space, navigation stays stable, and rendering is intentional, CLS disappears naturally — and users feel the difference.</p><blockquote><strong><em>Stable layouts build trust.<br> CLS is the metric that tells you when that trust breaks.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f135c68cb6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>