<?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 Igor Snitkin on Medium]]></title>
        <description><![CDATA[Stories by Igor Snitkin on Medium]]></description>
        <link>https://medium.com/@snigo?source=rss-585bf35838f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oxmQOzDQNBArJh9iAexh7w.jpeg</url>
            <title>Stories by Igor Snitkin on Medium</title>
            <link>https://medium.com/@snigo?source=rss-585bf35838f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 20:20:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@snigo/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[Styling a Design System]]></title>
            <link>https://snigo.medium.com/styling-a-design-system-4b344b9a447d?source=rss-585bf35838f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b344b9a447d</guid>
            <dc:creator><![CDATA[Igor Snitkin]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 14:09:04 GMT</pubDate>
            <atom:updated>2026-02-04T14:09:04.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOLP9mewGZL5mjGZUSpu3Q.png" /><figcaption>Image generated by Gemini</figcaption></figure><h4>Is Nothing Like Styling an App</h4><p>If your organization ships software, you have a design system. If you don’t maintain one on purpose, you retain one by accident.</p><p>As soon as you have more than one engineer, more than one screen, or more than one release, consistency becomes an operational concern rather than a <em>“nice to have.”</em> A design system is not just about polish or aesthetics; it is about coordination at scale. It is the shared contract that allows teams to move fast without drifting apart, and without it, every UI change quietly taxes velocity, consistency, and trust.</p><blockquote>Design system is not an option, it is the <strong>prerequisite for scale</strong>.</blockquote><p>Design systems come with no shortage of challenges: governance, distribution, versioning, adoption, and long-term maintenance. Here we’ll zoom in on just one — <strong>styling, </strong>and why styling a design system is not an extension of styling an app, but a fundamentally different problem with different trade-offs.</p><h3>The First Fork in the Road: Global vs. Local</h3><p>Every design system faces an early decision that looks like a trivial preference, but has real-world consequences:</p><blockquote>Do we ship one global CSS file, or styles per component?</blockquote><p>A single index.css feels safe and convenient—a single import, predictable ordering, no missing styles. Many classic frameworks, such as <a href="https://getbootstrap.com/">Bootstrap</a>, <a href="https://get.foundation/">Foundation</a>, and <a href="https://semantic-ui.com/">Semantic UI</a>, already follow this model, reinforcing the choice as familiar and well-tested.</p><p>For a long time, global stylesheets were the <em>only</em> <em>viable</em> option. In a pre-bundler era, CSS had no concept of reachability, no tree-shaking, and no reliable way to follow component usage. If you wanted predictable behavior, everything had to be global.</p><p>JavaScript bundlers changed that equation. Once imports became explicit, styles no longer needed to be <em>global to be reliable</em>. This shift explains why most modern component libraries default to per-component styling today.</p><blockquote>Tree-shaking is the obvious benefit — you only ship what you use</blockquote><p>As much as tree-shaking already looks convincing, it’s not the most important reason. <strong>Maintenance</strong> and <strong>scalability</strong> matter more over time.</p><p>Co-locating CSS, as well as tests, documentation, and stories with components, makes changes safer and reviews easier. Very few engineers enjoy navigating a 20,000-line stylesheet when refactoring a single component. Even teams that ultimately ship a single aggregated stylesheet often write their styles per component and compile them to a single deliverable later.</p><p>For the rest of this article, we’ll assume styles are authored and shipped per component.</p><h3>CSS, Sass, LESS, or SCSS</h3><p>Once we’ve established how to ship styles, let’s very briefly touch on CSS vs. popular CSS preprocessors, such as <a href="https://sass-lang.com/">Sass</a> (SCSS) and <a href="https://lesscss.org/">LESS</a>.</p><p>For years, the answer seemed obvious. CSS was too limited, too repetitive, and too hard to maintain at scale. Preprocessors filled the gaps with variables, nesting, mixins, and functions. They didn’t just improve ergonomics — they enabled otherwise impossible patterns.</p><p>Modern CSS has absorbed most of the features that originally justified preprocessors, essentially rendering them unnecessary for many projects. Native CSS now supports crucial features like <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Nesting"><strong>nesting</strong></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Cascading_variables/Using_custom_properties"><strong>variables (custom properties)</strong></a><strong>, </strong><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/color_value/color-mix"><strong>color-mix</strong></a><strong>,</strong> and many more, some of which we’ll discuss later in the article.</p><p>Apart from niche projects requiring complex logic and advanced mixins, there is no reason not to choose native, standards-compliant CSS.</p><h3>Separation of Concerns: Classes vs. Attributes</h3><p>Both classes and attributes have the same CSS specificity, and at first glance, look almost interchangeable. Both can equally be used for styling, neither feels particularly <em>“low-level”</em>, and, if anything, attributes often feel <em>more</em> expressive: key–value pairs read like state, not like arbitrary strings:</p><pre>&lt;Button className=&quot;button-primary&quot; /&gt;<br><br>&lt;Button data-variant=&quot;primary&quot; /&gt;</pre><p>For many engineers, including me, the <em>“attribute styling”</em> option was always very compelling. So why not lean into them?</p><h4>What we mean by “attribute styling.”</h4><p>When people advocate for attributes, they usually mean one (or likely both) of these patterns:</p><ol><li>The data-* global attributes</li><li>ARIA attributes</li></ol><pre>&lt;!-- data-* --&gt;<br>&lt;Button data-variant=&quot;primary&quot; data-size=&quot;lg&quot; /&gt;<br><br>&lt;!-- aria-* --&gt;<br>&lt;Button aria-pressed=&quot;true&quot; /&gt;</pre><pre>[data-variant=&quot;primary&quot;] { /* Style me */ }<br><br>[aria-pressed=&quot;true&quot;] { /* Style me */ }</pre><p>Both options are attractive for good reasons:</p><ul><li>They read like a declarative state</li><li>They avoid stringly-typed class names</li><li>They feel very familiar with component props</li><li>They don’t require you to merge internal and external classes</li></ul><p>In small components or one-off widgets, this can be perfectly fine. In a design system, it’s where problems start to surface.</p><h4>Why attributes start to break down at scale</h4><p>The issue isn’t that attribute selectors are <em>bad,</em> but because they have <strong>more than one responsibility at once</strong>. Nobody would think of using classes for dynamic data storage, so why think the other way?</p><p>ARIA in particular is dangerous here. ARIA attributes may change to improve accessibility without any visual change being intended. This happened with me in multiple teams: engineers were forced to remove or replace ARIA attributes, resulting in a visual breaking change.</p><h4>Why classes have an edge</h4><p>Sure, classes don’t look as elegant, but they have one decisive advantage:</p><blockquote>Classes exist <strong><em>only</em></strong> for one reason — styling.</blockquote><p>CSS classes don’t have semantic meaning; they don’t affect accessibility or store data. That makes them ideal as a <strong>styling contract</strong>: if it’s exposed by the design system, consumers are allowed to target it and override it.</p><p>There are also other practical considerations in favor of CSS classes:</p><ul><li>They are slightly more performant: class selectors are part of the <a href="https://chromium.googlesource.com/chromium/src/+/HEAD/third_party/blink/renderer/core/css/style-calculation.md"><em>“fast path”</em> in browser engines</a></li><li>They require less cognitive load to parse when reading</li><li>Tooling (linters, IDEs, IntelliSense) is highly optimized for them</li><li>Classes are easier to search, <a href="https://developer.chrome.com/docs/devtools/css#classes">toggle, and override</a> in DevTools</li></ul><blockquote>In a design system, classes are first-class citizens.</blockquote><p>This choice isn’t about syntax. It’s about responsibility.</p><ul><li><strong>ARIA attributes</strong> describe <em>accessibility semantics</em></li><li><strong>Data attributes</strong> store <em>configuration and metadata</em></li><li><strong>CSS classes</strong> describe <em>visual styling</em></li></ul><p>Let them all solve <strong>their own </strong>problems. That separation is what will keep styling predictable as the system grows.</p><h3>CSS Modules</h3><p>At this point, we’ve already established a pretty solid framework. We co-locate CSS files together with components, we use native CSS, and secure responsibility issues by exclusively using classes over other selectors.</p><p>There are two primary ways we can use classes inside components:</p><ul><li>Global CSS</li><li>Local CSS with CSS Modules</li></ul><pre>// Global<br>import { clsx } from &#39;clsx/lite&#39;<br><br>import &#39;./Button.css&#39;<br><br>&lt;button className={clsx(&#39;Button-primary&#39;, props.className)} /&gt;<br><br>// Local<br>import { clsx } from &#39;clsx/lite&#39;<br><br>import classes from &#39;./Button.css&#39;<br><br>&lt;button className={clsx(classes[&#39;Button-primary&#39;], props.className)} /&gt;</pre><p>In application code, styles are an implementation detail. Components are authored, consumed, and evolved within the same codebase, often by the same team. The primary risk is accidental coupling — a class name defined in one place unexpectedly affecting something elsewhere. CSS Modules solve that by making styles local by default. Class names are hashed, collisions disappear, and developers can stop worrying about the global namespace.</p><p>For apps, this is a clear win. The scoping is automatic, the mental model is simple, and the ergonomics are hard to argue with. <strong>Design systems don’t share that problem.</strong></p><p>A design system is not an application. Its styles are not an internal detail — they are part of the product it ships. Consumers don’t just render components; they compose them, extend them, and sometimes need to style around them. For that to work, the styling surface has to be <em>visible</em> and <em>predictable</em>.</p><p>Hashed class names make it impossible for consumers to target elements explicitly. This breaks the idea of styling as an API.</p><blockquote>An API can be private or public, but it cannot be opaque.</blockquote><p>Problems CSS Modules solve simply don’t exist at the design-system layer. Class collisions are not a bug there — they are an API problem that design systems are meant to solve <strong><em>explicitly</em></strong>.</p><p>For a design system, classes are not something to be hidden. They are something to be designed.</p><h3>BEM Is Dead. Long Live BEM.</h3><p>BEM has a reputation problem. For many engineers, it’s a relic from a pre-component era — verbose, rigid, and unnecessary in a world of scoped styles and modern frameworks. If you’d told me just a year ago that I would write about BEM, my answer would be</p><blockquote>“Yeah, right! Only if you build time machine and send me to Jurassic times”</blockquote><p>And yet, here we are — a chapter about <em>fricking</em> BEM!</p><p>For those who don’t know what BEM is, it’s a naming convention that structures class names around three concepts:</p><ul><li>Blocks</li><li>Elements</li><li>Modifiers</li></ul><pre>/* &lt;block&gt;__&lt;element&gt;--&lt;modifier&gt; */<br>.LoadingButton__SpinnerIcon--active { /* Style me */ }</pre><p>The goal is predictability — making relationships and constraints visible directly in the class name. Most importantly for us, BEM gives an arbitrary class name a structure — exactly what the <em>“styling as an API”</em> concept requires.</p><p>If you inspect <a href="https://ui.shadcn.com/docs/directory">modern component libraries</a>, you will find that most separate components into two groups: <strong>primitives</strong> and <strong>blocks</strong> (aka “atoms” and “molecules” in the <a href="https://atomicdesign.bradfrost.com/chapter-2/">Atomic Design</a>), which fits perfectly into the BEM model:</p><ul><li>Blocks → <strong>B</strong>locks</li><li>Primitives → <strong>E</strong>lements</li><li>Prop invariants → <strong>M</strong>odifiers</li></ul><p>While I wouldn’t recommend BEM for the application styling, it seems like a pretty damn good match for the design system!</p><h3>Resolving Invariant Explosions</h3><p>Of course, BEM comes with issues of its own — particularly in the <strong>modifier</strong> layer.</p><p>Modifiers are where variation lives, and variation is where design systems tend to get messy. Left unchecked, modifier classes can drift from being descriptive to being ambiguous, overloaded, and subtly interdependent. None of this is a flaw in BEM itself, but it <em>is</em> where naïve usage starts to break down at scale.</p><h4>Ambiguous modifiers</h4><p>A class like Button--lg looks harmless enough. It clearly communicates that the button is “large,” and it’s easy to apply. The problem is that it’s also <em>incomplete</em>.</p><p>What does <em>“lg”</em> refer to? Size? Padding? Typography? And how does it map back to the component’s props interface? A modifier value without its key loses context the moment it leaves the component implementation.</p><p>This ambiguity becomes a <em>real</em> problem once components grow. If lg means size here and density there, collisions are inevitable — not at the CSS level, but at the semantic one.</p><p>The fix is simple and boring: <strong>make the key explicit.</strong></p><blockquote>Verbosity buys clarity. Clarity buys scale.</blockquote><p>Button--size-lg may be longer, but it’s unambiguous. The modifier name now mirrors the component prop, makes intent obvious in markup, and leaves room for other dimensions without the risk of overlap.</p><h4>Invariant explosions</h4><p>The second issue is more subtle — and more dangerous.</p><p>As components mature, modifiers often stop being independent. A Button--variant-primary might require different colors when combined with Button--color-destructive. A size modifier might need special casing when icons are present. Very quickly, modifiers start depending on other modifiers.</p><p>This is commonly known as <strong>invariant explosions</strong>.</p><p>The usual response is to encode these combinations directly in CSS: more selectors, more conditions, more branches. The result is a growing matrix of modifier combinations that becomes harder to reason about with every new variant.</p><p>We need a more scalable solution — <strong>restrict</strong> what modifiers can do.</p><p>Modifier classes should <strong>not own</strong> styling rules. Instead, they should set CSS variables that describe intent — values like spacing, colors, or emphasis levels. The actual styling logic then lives in block- and element-level rules that consume those variables.</p><pre>/* ❌ never this */<br>.Button--variant-primary.Button--color-destructive { … }<br><br><br>/* ✅ Rule explosion &gt; Selector explosion */<br>.Button {<br>  background-color: var(--button-bg);<br>  color: var(--button-fg);<br>}<br><br>/* Color modifiers set internal palette vars */<br>.Button--color-default {<br>  --button-palette-bg: var(--color-bg-default);<br>  --button-palette-fg: var(--color-fg-default);<br>}<br><br>.Button--color-destructive {<br>  --button-palette-bg: var(--color-bg-destructive);<br>  --button-palette-fg: var(--color-fg-on-destructive);<br>}<br><br>/* Variant modifiers map internal palette to behavior */<br>.Button--variant-primary {<br>  --button-bg: var(--button-palette-bg);<br>  --button-fg: var(--button-palette-fg);<br>}</pre><p>In this model, Button--variant-primary doesn’t define colors directly. It defines what kind of button this is. The button’s elements decide how that intent is expressed. The resulting structure is closer to a <strong>state machine</strong> than a collection of conditional selectors: modifiers define state, and elements derive behavior from it.</p><blockquote>BEM provides the structure. CSS variables provide the flexibility.</blockquote><h4>Rule explosion &gt; selector explosion</h4><p>As you might have noticed, we haven’t really solved the explosion itself— the combination of interdependent states will happen no matter what. What we can do, however, is to decide <em>what</em> to explode:</p><p>A. <strong>Rule explosion</strong>: keep selectors as flat as possible by increasing the number of rules</p><p>B. <strong>Selector explosion</strong>: keep rules as DRY as possible by increasing selectors&#39; complexity</p><p>On the surface, the choice seems to be a matter of preference, yet again, it has real-world implications, and this is where design systems need to be extra careful.</p><p>Combining selectors <em>increases</em> CSS specificity. It encodes assumptions about composition and ordering. And most importantly, it changes the <em>weight</em> of rules in ways that are hard to undo without escalation. What looks like elegance in an app layer becomes rigidity in a design system layer.</p><blockquote>A design system should aim for the lowest reasonable CSS specificity. Anything higher becomes friction for the consumer.</blockquote><p>Rule explosion keeps specificity flat and predictable. Selector explosion does the opposite. The goal isn’t the fewest lines of CSS, but preserving the ability to evolve without breaking consumers.</p><h4>Pseudo-classes are <em>not</em> modifiers</h4><p>One critical mistake engineers could make at this stage is to treat pseudo-classes as modifiers. Doing this will cause invariant leaks and all sorts of other issues. Modifier classes <strong><em>select the design-system state</em></strong>. Pseudo-classes <strong><em>express how elements behave</em></strong> in response to user interaction or platform conditions.</p><pre>/* ❌ never do this */<br>.Button:hover {<br>  --button-bg: var(--button-palette-bg-hover);<br>}<br><br>/* ✅ Treat pseudo-classes as element-level classes */<br>.Button:hover {<br>  background-color: var(--button-bg-hover);<br>}</pre><h3>Conflict Management</h3><p>Now, when we have outlined a framework for frictionless overrides, consider the following example:</p><pre>&lt;style&gt;<br>  .custom-size {<br>    height: 21px;<br>  }<br>&lt;/style&gt;<br><br>&lt;Button className=&quot;custom-size&quot; /&gt;</pre><p>Both .custom-size and internal .Button--size-* have the same specificity. How can we be sure the custom override will work?</p><p>In an app, the answer is often “import order” or “it happens to work.” In a design system, <em>“happens to work”</em> is not a sufficient contract.</p><p>When specificity ties, the cascade falls back to source order: the rule that appears <em>later</em> wins. But when styles are shipped as a library, the consumer does not reliably control where your component CSS lands relative to their own CSS. Build tools, code-splitting, dependency deduplication, and injection order can all reorder things in ways that are invisible at the call site.</p><p>So if we want frictionless overrides, we need a deterministic rule for <strong>order</strong>, not just a rule for <strong>specificity</strong>.</p><h4>Enter the layer: explicit order for the cascade</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@layer"><strong>Cascade layers</strong></a> are the new addition to modern CSS that let you define a global ordering that is independent of file order. You can decide, up front, what categories of CSS should win, and the browser will honor that order consistently.</p><p>In the cascade, <em>unlayered</em> rules sit in an implicit <em>“top”</em> layer above all named layers (unless !important gets involved). So if we scope all internal styles in their own layer, the .custom-size class will <em>always</em> override the internal .Button--size-*</p><pre>/* Button.css */<br><br>@layer design-system {<br>  /* place CSS rules here */<br>}</pre><h4>Boilerplate scripts</h4><p>To avoid engineers or AI agents accidentally forgetting to nest CSS rules, we can write a simple script that will generate boilerplate files, including CSS with pre-written layer</p><pre>ds add element Button<br>ds add block LoadingButton</pre><h4>Cascade layers ordering</h4><p>What happens when a consumer uses <a href="https://tailwindcss.com/">Tailwind</a> and expects utility classes to override a design system component?</p><pre>&lt;Button className=&quot;h-[21px]&quot; /&gt;</pre><p>Tailwind already organizes its styles using cascade layers: base, components, and utilities. If a design system also relies on the layer, the interaction between the two becomes a matter of <strong>explicit ordering</strong>, not selector tricks.</p><p>To make this predictable, the design system should declare its own layer and ensure it sits <em>before</em> Tailwind’s native layers:</p><pre>/* main.css */<br>@layer design-system, base, components, utilities;</pre><p>With this order, Tailwind utilities naturally win over design system component styles, without the need to increase specificity or rely on import order.</p><h3>Two Elephants in the Room</h3><p>At this point, it’s worth addressing the opinionated nature of this article and speaking about two giant elephants in the room:</p><p><strong>Tailwind</strong> and <strong>CSS-in-JS</strong>.</p><p>Why haven’t we just used Tailwind or a CSS-in-JS library, like <a href="https://emotion.sh/docs/introduction">Emotion</a>? Both are very popular and are widely used by adopted component libraries today. So if this article argues for something else, it’s fair to ask whether that’s a limitation — or a deliberate choice.</p><blockquote>This is a choice. Not a verdict.</blockquote><h4>Elephant 1: Tailwind</h4><p>Tailwind is a great tool — especially for application development. It shines at rapid composition, makes layout work trivial, and gives teams a shared vocabulary. If that’s the experience you want, <em>Tailwind delivers</em>.</p><p>The trade-off is that Tailwind is not just a styling approach; it’s a dependency that shapes the entire consumer environment. To use a Tailwind-based design system, consumers <em>must</em> adopt Tailwind themselves, configure it correctly, keep it up to date, and align on conventions like theme tokens and build setup.</p><p>This article explores a different constraint: a design system that can be consumed by teams using plain CSS, Tailwind, or something else entirely — without requiring them to switch. A simple unopinionatad, drop-in library.</p><h4>Elephant 2: CSS-in-JS</h4><p>CSS-in-JS libraries solve a different set of problems, and they <em>solve them well</em>. Like CSS modules we’ve descussed, they provide scoped styles, dynamic theming, co-location, and runtime guarantees are compelling features — especially in large applications with complex state.</p><p>But like Tailwind, CSS-in-JS is a <em>contagious</em> dependency.</p><p>A design system built on styled-components or emotion requires consumers to install the same runtime, align versions, understand its APIs, and accept its performance and debugging characteristics. Even when abstracted away, the dependency leaks through theming, overrides, and extension points.</p><p>Again, this is not inherently bad. It’s just a constraint.</p><p>Once styling depends on a runtime, the design system stops being a simple package and becomes an <strong>ecosystem commitment</strong>. If that’s a commitment you’re willing to take — great! If you’re not sure, consider following…</p><h4>Why plain CSS</h4><p>Plain CSS is not neutral because it’s old. It’s neutral because it’s <strong>universal</strong>.</p><p>Every frontend stack understands it. Every build tool can process it. Every styling approach — Tailwind, CSS-in-JS, inline styles, you name it — can interoperate with it. That makes plain CSS uniquely suited for libraries that aim to be dropped into <em>many</em> environments without dictating how teams work elsewhere.</p><p>This article argues for a model where CSS is treated as an API: explicit, predictable, and intentionally constrained. That model doesn’t preclude Tailwind or CSS-in-JS. It simply doesn’t require them.</p><p>Consumers who want Tailwind can still use it — for layout, composition, or even variable overrides. Consumers who prefer CSS-in-JS can wrap components or build higher-level abstractions. The design system stays usable either way.</p><p>That flexibility is the point.</p><p>If you resonate with the article and would like to teach your AI agent a new skill, download it <a href="https://gist.github.com/snigo/ed2a53c832132080bc4e7dbdb0190bff">here</a>.</p><p>☮️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b344b9a447d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Only Article You Need to Understand Floating-Point Numbers]]></title>
            <link>https://snigo.medium.com/the-only-article-you-need-to-understand-floating-point-numbers-1534a9ad973b?source=rss-585bf35838f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1534a9ad973b</guid>
            <dc:creator><![CDATA[Igor Snitkin]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 12:48:51 GMT</pubDate>
            <atom:updated>2026-01-29T12:48:51.817Z</atom:updated>
            <content:encoded><![CDATA[<h4>And Why 0.1 Is Weird</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDJQ44W9AnANcUMYKTy1NQ.png" /><figcaption>Image generated by Google’s Nano Banana Pro</figcaption></figure><h3>The Lie We All Learned: “Computers Can Do Math”</h3><p>We’ll start with something that looks absurd</p><pre>0.1 + 0.2 === 0.3<br>// false</pre><p>If you’ve ever seen this, your first reaction was probably:</p><blockquote>“JavaScript is trash! This would never happen in <strong>a proper</strong><em> </em>language!”</blockquote><p>And then you moved on, never questioning the issue. But here’s the uncomfortable truth:</p><blockquote>The computer is not wrong.<br>You are asking the wrong question.</blockquote><h4>The result that broke the trust</h4><p>Most of us learned arithmetic long before we learned programming. By the time we write our first line of code, math already feels <em>settled</em>.</p><p>So when a computer says:</p><pre>0.1 + 0.2 // 0.30000000000000004</pre><p>…it feels like betrayal, while what’s actually happening is something far more subtle:</p><ul><li>The computer is doing exactly what it was designed to do</li><li>You are assuming it works as humans do</li><li>And calculators quietly reinforce that assumption every day</li></ul><h4>Calculators vs computers</h4><p>Try this on your phone’s calculator app 0.1 + 0.2 and you’ll get 0.3. Clean, reassuring, and correct! Correct?</p><p>So what’s going on, who’s right?</p><p>A. Is the calculator smarter?</p><p>B. Is the computer broken?</p><p>C. Or is something deeper going on?</p><p>(Answer: C)</p><h4>Two different contracts</h4><p>A calculator and a programming language answer <strong>different questions</strong>. A calculator answers: <strong>“What number did the human <em>mean</em>?” </strong>A programming language answers: <strong>“What number do I <em>actually have</em>?”</strong></p><p>Those are not the same question. Calculators are designed to protect <em>your intuition</em>. Programming languages are designed to protect <em>your data</em>.</p><p>Once you see that, the weird results stop being bugs and become consequences.</p><h4>The uncomfortable premise of this article</h4><p>Here’s the premise we’ll build on:</p><blockquote>Computers do not store numbers. They store approximations of numbers.</blockquote><p>The moment you accept that, everything else starts to make sense. We’ll dive into and explore why 0.1 is problematic, why some numbers are perfectly safe, why integers <em>“break”</em> at large sizes, why printing a number is much harder than you think, and why we don’t <em>“just use decimals”.</em></p><p>The ultimate goal of this article is to make 0.1 + 0.2 no longer feel weird. Remember:</p><blockquote>Floating-point numbers aren’t broken, they’re answering a different question than you think.</blockquote><p>Let’s see what question that is.</p><h3>Humans Numbers vs Computers Numbers</h3><p>When you write0.1, it feels like you’re giving the computer an obvious instruction: <em>store this number for me. </em>You’re not. You’re giving it an <strong>idea</strong>, and it has to translate that idea into something physical.</p><p>That translation is where everything starts to drift.</p><h4>Ten fingers</h4><p>We count in <strong>tens</strong> only because we have ten fingers. That’s not a joke!</p><p>As a result, our entire number system is built around powers of 10: <strong>10, 100, 1000, 0.1, 0.01</strong>, and so on. When we see 0.1, we intuitively read it as an exact number — one tenth. There’s no ambiguity in our heads.</p><p>Computers do <strong>not</strong> count in tens. They count in <strong>twos</strong>.</p><p>Some fractions are impossible to write exactly in base-10:</p><pre>1 / 3 // 0.333333333333333…</pre><p>And some fractions are impossible to write exactly in base-2:</p><pre>1 / 10 // 0.0001100110011001100110011… (it never ends…)</pre><p>As computers cannot store an infinite number of digits, they have to stop somewhere and say:</p><blockquote>“Alright! This is close enough.”</blockquote><p>That decision is <strong>not optional</strong>. It is unavoidable.</p><h4>Representation is not a value</h4><p>The number you write, and see on the screen of your computer (spoiler: and calculator), is <strong>not the number the computer stores</strong>. Computers store <strong>best guesses</strong> under strict constraints:</p><blockquote>A computer has infinite range, but finite precision.</blockquote><p>It can represent very small and very large numbers, but only with a limited amount of detail. As numbers get larger, that detail gets coarser, and as representations get tighter, approximations appear.</p><p>So what about your calculator? It absolutely (except for a few exceptions) has the same problem! It just chooses to hide it.</p><p>Calculators are designed to <strong>protect intuition</strong>, not data integrity.<br>Programming languages are designed to <strong>protect correctness</strong>, not comfort.</p><p>We’ll come back to this later — and when we do, it’ll hopefully make sense why both behaviors are reasonable.</p><blockquote>Floating-point problems don’t start with arithmetic. They start with representation.</blockquote><p>Let’s dive a bit deeper and build a computer!</p><h3>A Very Slow Computer</h3><p>Forget about programming languages, CPUs, and optimizations for a second. Imagine instead that <strong>you are the slowest computer in the world</strong>. You can:</p><ul><li>store bits (0 and 1)</li><li>multiply and divide by 2</li><li>keep a fixed number of bits in memory</li></ul><p>And now the task: <strong>“Store the number </strong><strong>0.1”.</strong></p><h4>Step 1: What does 0.1 even mean?</h4><p>As the slowest computer in the world, you don’t understand <em>tenths. </em>You only understand <strong>powers of two. </strong>So, before you can store0.1, you have to translate it into binary format. In other words, you have to answer:</p><blockquote>“Can I express one tenth as a sum of 1/2, 1/4, 1/8, 1/16, …?”</blockquote><p>If yes, you’re safe! If no, you’re forced to approximate.</p><h4>Step 2: Convert 0.1 to binary</h4><p>In case you skipped computer science classes in school, the process is fairly straightforward:</p><pre>x = 0.1<br>repeat:<br>  x = x × 2<br>  bit = floor(x)<br>  x = x - bit</pre><p>Let’s run it! 🚀</p><pre>|   Step   |   x × 2   |   Bit   |<br>| -------- | --------- | ------- |<br>|     1    |    0.2    |    0    |<br>|     2    |    0.4    |    0    |<br>|     3    |    0.8    |    0    |<br>|     4    |    1.6    |    1    |<br>|     5    |    1.2    |    1    |<br>|     6    |    0.4    |    0    |<br>|     7    |    0.8    |    0    |<br>|     8    |    1.6    |    1    |<br>|     …    |    …      |    …    | </pre><p>You start seeing a pattern:</p><pre>0.0001100110011001100110011…</pre><p>You’ve just discovered the problem 😨</p><h4>Step 3: Panic</h4><p>As the slowest computer in the world, you now realize something terrifying:</p><blockquote>“Oh boy, I will never finish writing this number.”</blockquote><p>This is not a bug. This is basic math. Just like 1 / 3 never ends in decimal,<br> 1 / 10 never ends in binary.</p><blockquote>“OK, at this very moment, I say we sit tight and assess”</blockquote><h4>Step 4: Normalize the Gibberish</h4><p>Before we deal with the infinite sequence problem, let’s talk about the format that allows you, the slowest computer in the world, to understand that 1010101 gibberish is actually a number.</p><p>You don’t store numbers as long strings of bits and <em>hope</em> they mean something. You store them in a structure. A very specific structure:</p><pre>1.xxxxx × 2^E</pre><p>This is binary scientific notation. Just like decimal scientific notation, it has two parts:</p><ul><li>The significand (or mantissa)</li><li>The exponent</li></ul><p>When we write 3.33E-1 in decimal, we mean a 3.33 coefficient (the significand) of 10^-1 (the exponent).</p><p>When we write 1.101001001E-3 in binary, we mean 1.101001001 fraction of 2^-3. As computer scientists, we try to be as efficient as possible, and we notice that 1. part of the binary fraction will always be the same, so we can be <em>smart</em> — assume it’s there and actually store only the bits after the dot: 101001001</p><p>To count the exponent, we will follow the IEEE-754 standard and shift our bits to the left until the first bit is 1:</p><pre>0.000110011…<br>↓ shift right 4 times<br>1.100110011… × 2⁻⁴</pre><p>Now you’ve learned two things:</p><ul><li>The <strong>exponent</strong> is -4</li><li>The <strong>fraction</strong> starts with 100110011…</li></ul><p>Good progress!</p><h4>Step 5: Dedicate storage</h4><p>You are only allowed to store a fixed number of bits. Let’s be generous and dedicate 64 bits to store 0.1. That corresponds to the so-called double-precision floating-point format, also known as <strong>float64/f64</strong> (or <strong>double</strong> in many older programming languages).</p><p>JavaScript/TypeScript calls it number and Python calls it float — both use float64 under the hood.</p><p>We’ll distribute the 64-bit budget in the following way:</p><ul><li>1 bit for the sign: 0 for + and 1 for -</li><li>11 bits for the exponent</li><li>52 bits for the fraction</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waAiZtXcQWGhIcQptl320A.png" /></figure><p>That gives us 11 bits of the exponent and <strong>53 bits</strong> of the fraction — remember the first 1 from the previous step, we always imply.</p><p>Now feel free to go and shock your peers with:</p><blockquote>“Why is MAX_SAFE_INTEGER = 2^53 − 1 if the mantissa is only 52 bits?”</blockquote><p>Congrats! You have a solid condition to stop your infinite loop from Step 2: once you encounter the implied (aka hidden) bit, count 52 bits + some more to apply correct rounding in the next step.</p><h4>Step 6: Commit the Bits</h4><p>At this point, you, the slowest computer in the world, have done all the thinking you had to do. Now it’s time to <strong>commit</strong> the number to memory!</p><p>You have the sign 0 for +!</p><p>To store an exponent, you need an unsigned integer using a trick from the IEEE-754 standard:</p><pre>storedExponent = E + bias // bias = 1023 for float64<br><br>E = -4<br>storedExponent = 1019 // 01111111011</pre><p>Before committing fraction bits, as mentioned, we first need to round them. If you’re not just slow, but also a lazy computer, you might ask, why not just take 52 bits? Because that would mean truncation, and instead of rounding <strong>noise,</strong> you’ll get a stable rounding <strong>drift: </strong>every stored value is slightly <strong>less</strong> than the real</p><ul><li>Truncation — Over many operations, errors stably accumulate</li><li>Rounding — Over many operations, errors statistically cancel out</li></ul><p>Luckily for you, the rounding algorithm is described in the IEEE-754 standard, and is not significant for this article — what’s important is that:</p><ul><li>Rounding happens</li><li>The extra bits you saved to calculate rounding <strong>are thrown away and lost forever</strong></li></ul><p>And so, you store:</p><pre>0 (sign +)<br>01111111011 (exponent 1019 in binary)<br>1001100110011001100110011001100110011001100110011010 (fraction)</pre><p><strong>64 bits of success!</strong></p><p>You can inspect any 64-bit float in JavaScript by using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView">DataView</a>:</p><pre>// Take 8 bytes (64 bits)<br>const buf = new ArrayBuffer(8)<br>// Create DataView<br>const dw = new DataView(buf)<br>// Set 0.1 on position 0<br>dw.setFloat64(0, 0.1)<br>// Read as int64 in padded binary format<br>dw.getBigUint64(0).toString(2).padStart(64, &#39;0&#39;)<br><br>// &#39;0011111110111001100110011001100110011001100110011001100110011010&#39;</pre><h3>53 bits of precision</h3><p>What do 53 bits give us? It’s not 53 decimal digits — bits are in binary. What this really means is that the significand can distinguish 2<strong>⁵³ different values</strong>.</p><p>To estimate how many <strong>decimal digits</strong> that corresponds to, we need a bit of math:</p><pre>// 10^d ≈ 2^53<br>const d = 53 * Math.log10(2) // 15.954589770191003</pre><p>What does <strong>15.95</strong> tell us? It tells us that arithmetic operations with numbers containing 16 significant digits, and resulting in such numbers, are <strong>usually safe</strong>. And if you need <strong>always safe</strong>, your limit is 15 digits.</p><p>Significant digits are <strong>all digits in the number</strong>, regardless of where the decimal point is:</p><pre>0.123456789012345 // usually safe<br>90.12345678901234 // usually safe<br>789.0123456789012 // usually safe<br>// ...<br>67890123456789.01 // usually safe<br>123456789012345.6 // usually safe<br><br>0.12345678901234 // always safe<br>90.1234567890123 // always safe<br>789.012345678901 // always safe<br>// ...<br>6789012345678.91 // always safe<br>12345678901234.5 // always safe</pre><p>Now, if you’re reading carefully, your brain has to ask:</p><blockquote>Why 0.1 + 0.2 doesn’t give an exact answer? Both numbers are well below 15 digits?!</blockquote><p>Good question! Before answering it, let’s talk about integers.</p><h4>Integer precision</h4><p>All integers in <strong>float64</strong> are exactly representable within:</p><pre>MIN_SAFE_INTEGER ≤ N ≤ MAX_SAFE_INTEGER</pre><pre>// In JavaScript<br><br>const SAFE_INTEGER = 2 ** 53 - 1<br>Number.MIN_SAFE_INTEGER === -SAFE_INTEGER; // true<br>Number.MAX_SAFE_INTEGER === SAFE_INTEGER; // true</pre><p>Contrary to popular belief, beyond this point, nothing overflows, nothing wraps, and numbers simply lose <strong>detail.</strong></p><p>Near zero, the number line of integers looks nice and dense:</p><pre>… 1, 2, 3, 4, 5 …</pre><p>Beyound 2^53, the spacing increases:</p><pre>… 9007199254740992,<br>  9007199254740994,<br>  9007199254740996 …</pre><p>For example, when you do addition beyond this point, you&#39;ll notice that odd integers disappear:</p><pre>Number.MAX_SAFE_INTEGER + 1 // 9007199254740992<br>Number.MAX_SAFE_INTEGER + 2 // 9007199254740992<br>Number.MAX_SAFE_INTEGER + 3 // 9007199254740994<br>Number.MAX_SAFE_INTEGER + 4 // 9007199254740996</pre><p>And contrary to even more popular belief, this is not a JavaScript quirk. This exact format is used by <strong>C, C++, Java, Python, Go, Rust,</strong> and many more.</p><p><strong>The JavaScript quirk</strong></p><p>Of course, our beloved JavaScript wouldn’t be itself without quirks.</p><p>Because it has only one numeric type, bitwise operators silently coerce numbers to <strong>32-bit signed integers</strong>:</p><pre>Number (float64)<br>   ↓<br>32-bit signed integer<br>   ↓<br>bitwise operation<br>   ↓<br>Number (float64)</pre><p>So before you brag, “You can use | 0 instead of Math.floor“, you might consider this quirk first:</p><pre>const bigFloat = 2.34 ** 32 // 652991363220.9714<br><br>~~bigFloat                  // 156334228<br>bigFloat | 0                // 156334228<br>bigFloat &gt;&gt; 0               // 156334228</pre><p><strong>The noise you don’t see</strong></p><p>So why 0.1 + 0.2 “fail”? If you remember the uncomfortable premise of this article, computers store the approximation of numbers, and what you see on the screen is not what is stored:</p><blockquote>The computer hides from you the noise it considers not relevant</blockquote><p>Try this:</p><pre>(0.1).toPrecision(55)<br>// &#39;0.1000000000000000055511151231257827021181583404541015625&#39;<br><br>(0.2).toPrecision(55)<br>// &#39;0.2000000000000000111022302462515654042363166809082031250&#39;</pre><p>That’s far more than 15 “safe” significant digits, isn’t it?</p><p>If you’re impatient like me, you can jump to a somewhat premature conclusion:</p><blockquote>“Oh, I get it! When adding those, sometimes you get a carry-over.”</blockquote><p>Ok! Let’s try that!</p><pre>const s1 = (0.1).toPrecision(55)<br>const s2 = (0.2).toPrecision(55)<br><br>addStrings(s1, s2)<br>// 0.3000000000000000166533453693773481063544750213623046875<br><br>(0.1 + 0.2).toPrecision(52)<br>// 0.3000000000000000444089209850062616169452667236328125</pre><p>Why don’t these match? To understand why, we need to understand how computers add numbers.</p><h3>Addition Is Not Decimal Addition</h3><p>At this point, we’ve done something <em>very </em>important. We stopped talking about <em>numbers </em>and started talking about <em>representations</em>.</p><p>Adding approximations brings us into the scary waters of the <a href="https://en.wikipedia.org/wiki/Propagation_of_uncertainty">Propagation of uncertainty</a></p><blockquote>“When we add two approximations together, <strong>their absolute errors accumulate.</strong>”</blockquote><p>Let’s add 0.1 and 0.2 together. As we learned in the world’s slowest computer chapter, both numbers are stored using binary scientific notation:</p><pre>1.100110011001100110011… × 2⁻⁴<br>1.100110011001100110011… × 2⁻³</pre><p>Same fraction, different scales.</p><h4>Step 1: Align the exponents</h4><p>Before adding anything, the computer must rewrite both numbers so they share the <strong>same exponent</strong>. This is the first step of floating-point addition.</p><p>The smaller number is shifted to match the exponent of the bigger number</p><pre>0.2 → 0.1100110011… × 2⁻⁴</pre><p>Did you notice it? We lost a bit of precision <em>before</em> adding anything</p><blockquote>Right-shifting loses information</blockquote><p>This loss is the first <strong>unavoidable</strong> error.</p><h4>Step 2: Add the significands</h4><p>Now that the exponents match, the computer adds the significands:</p><pre> 1.100110011…<br>+<br> 0.110011001…<br>----------------<br>10.010001100…</pre><p>Note that this is pure binary integer addition. No decimals. No tenths. No base-10 intuition. Just bits.</p><p><strong>Step 3: Normalize</strong></p><p>As the resulting number doesn’t fit the required form, it has to be normalized:</p><pre>10.010001100… × 2⁻⁴<br>↓<br>1.0010001100… × 2⁻³</pre><h4>Step 4: Round to fit</h4><p>The result significand now contains an extra bit that cannot fit in the mantissa, and the computer performs a “rounding to even” procedure, which creates a probability of the last bit-52 to be flipped in about 25% of cases:</p><pre>G = 0 AND b52 = 0 // FALSE (no flip)<br>G = 1 AND b52 = 0 // FALSE (no flip)<br>G = 0 AND b52 = 1 // FALSE (no flip)<br>G = 1 AND b52 = 1 // TRUE (flip)</pre><p>In our case, adding significands caused:</p><pre>10.010001100110011001100110011001100110011001100110011<br>↓<br>1.001000110011001100110011001100110011001100110011001 G=1<br>↓<br>1.001000110011001100110011001100110011001100110011010 Rounded up</pre><p>This rounding is our second <strong>unavoidable </strong>error<strong>. </strong>The mantissa was incremented by 1 ULP, which produced the nearest representable double: 0.30000000000000004</p><p>Tada 🎉</p><h4>Recipe for the error</h4><p>Of course, the rounding error is not specific to 0.1 + 0.2. Many pairs of numbers produce the same behaviour. Every time the following conditions are met, we see the error:</p><ol><li>Inputs are approximations</li><li>Approximation errors point in the same direction — both larger or smaller than the original number</li><li>Approximations have different exponents (magnitudes differ)</li><li>The result of the addition exceeds the mantissa capacity</li></ol><p>The list above also gives us some reassurance. For example, we know for sure that rounding error will never occur for the powers of two.</p><pre>// 2^k<br>0.23423417 + 2 // always safe<br>0.23423417 * 4 // always safe<br>0.23423417 / 0.125 // always safe<br><br>// doubling the number<br>const a = 0.171<br>a + a; // always safe (equivalent of a * 2)</pre><h3>Printing Numbers (Is Surprisingly Hard)</h3><p>By now, we’ve done something impressive. We’ve stored approximations, added them together, rounded correctly, and ended up with a perfectly valid floating-point number.</p><p>It seems like the hard part is over, and all we have to do is just print the result on the screen. Except… <strong>printing is harder than anything we’ve done so far</strong>.</p><p>Remember, the computer only stores the approximation and has no idea what decimal this approximation represents.</p><h4>The illusion of “the number”</h4><p>When you ask the computer to “show me the number”, you are really asking:</p><blockquote>“Please convert this binary approximation into a decimal string that a human will accept.”</blockquote><p>A tempting approach would be <em>“Convert the binary number to decimal and print the first N digits.”</em></p><p>Feels reasonable, but also wrong. You might notice a theme, with the truncation being <strong>bad</strong>.<strong> </strong>Again.</p><p>Consider this:</p><pre>0.30000000000000001 === 0.30000000000000002 // false</pre><p>The two numbers above have different binary approximations. If we truncate them to 16 decimal places, whatever the user reads will be different from the stored value. And before you tell me, “Let’s just truncate to 17 places”:</p><pre>0.30000000000000002 === 0.30000000000000003 // true</pre><p>We need something more sophisticated here</p><h4>Round-trip safety</h4><p>Modern number printers are built around one core rule</p><blockquote>If a number is printed and then read back, the original value must be recovered exactly</blockquote><p>This is called <strong>round-trip safety</strong>. And not only that, but we also need the <strong>shortest</strong> representation of that number. In other words, the printer must “prettify” numbers to the lowest possible precision, resulting in the same approximation.</p><p>That’s why you see 0.30000000000000004 on your screen — 0.3 parses to a different number and does not guarantee the round-trip safety.</p><pre>(0.3).toPrecision(55)<br>// 0.2999999999999999888977697537484345957636833190917968750<br><br>(0.30000000000000004).toPrecision(55)<br>// 0.3000000000000000444089209850062616169452667236328125000</pre><p>Modern runtimes use sophisticated algorithms to print the number, like <a href="https://github.com/ahaldane/Dragon4/blob/master/Dragon4.cpp">Dragon4</a>, <a href="https://github.com/ulfjack/ryu">Ryu</a>, <a href="https://github.com/vitaut/schubfach">Schubfach</a>, etc.</p><h3>Other Number Systems (and When to Use Them)</h3><p>Up to now, we’ve been deliberately unfair to floating-point numbers.</p><p>We asked them to do something they have never been designed to do, like represent decimals exactly, behave like integers, and agree with human intuition.</p><p>So instead of blaming floating-point, let’s see what other number systems exist and what problems <em>they</em> were designed to solve.</p><h4><strong>Floating-point (what we already know)</strong></h4><p>Let’s quickly restate the pros and cons of floating-point numbers</p><p><strong>Good for:</strong></p><ul><li>huge range</li><li>fast hardware operations</li><li>approximate real numbers</li><li>scientific and physical computation</li></ul><p><strong>Bad for:</strong></p><ul><li>money</li><li>exact decimals</li><li>unbounded integers</li></ul><h4>Integers (fixed-width)</h4><p>The simplest and the oldest numeric type</p><p><strong>Good for:</strong></p><ul><li>exact and predictable calculations</li><li>fastest hardware operations</li></ul><p><strong>Drawbacks:</strong></p><ul><li>accidental overflows and wrapping (in some languages)</li><li>no fractions</li></ul><h4>Scaled integers (aka the “money trick”)</h4><p>Store values as integers, but agree on an implicit fixed scale. For example, we store:</p><ul><li>dollars as <strong>cents</strong></li><li>seconds as <strong>milliseconds</strong></li><li>percentages as <strong>basis points</strong></li></ul><p>This gives you great performance and predictability of integers, at a cost of extra mental overhead and fixed precision. Good for basic money operations — anything that doesn’t require division should work ok:</p><ul><li>Calculating totals</li><li>Cash movements</li><li>Ledger posting and UI formatting</li></ul><h4>Decimal floating-point (BigDecimal, Decimal.js)</h4><p>If binary numbers are so problematic, why not just store them as decimals? This is exactly what the <strong>BigDecimal (</strong>Java) and <strong>decimal.js</strong> do. They store numbers as objects in a format:</p><pre>{<br>  coefficient: number // or number[] for the arbitrary precision<br>  exponent: number<br>  sign: number<br>}</pre><p>Looks familiar? 😃 Storing 0.1 becomes a hassle-free operation — no infinite expansion, no approximation.</p><p><strong>Trade-offs:</strong></p><ul><li>Slower arithmetic operations</li><li>Finite precision</li></ul><p>We use BigDecimal for complex financial operations requiring division, like interests and accrual calculations, FX (Foreign Exchange), taxes and commissions, payroll, etc.</p><h4>Arbitrary-precision integers (BigInt)</h4><p>Some languages let integers grow without bound:</p><ul><li>JavaScript: BigInt</li><li>Python: int</li><li>Java: BigInteger</li></ul><p>Numbers stored in big integers never overflow or lose precision, and grow as large as memory allows</p><p><strong>Trade-offs:</strong></p><ul><li>they cannot represent fractions</li><li>not hardware-accelerated — slower than fixed-width integers</li></ul><p>We use arbitrary-precision integers when numbers get high and precision matters.</p><h4>Choosing the right tool</h4><blockquote>There is no “best” number type — only the right one for the job</blockquote><p>As much as floating-point numbers are perfect tool allowing you to cover maximum amount of cases, sometimes they are not the best choice for the job.</p><h3>Conclusion</h3><p>The ultimate goal of this article was simple:</p><blockquote>Make 0.1 + 0.2 stop feeling weird.</blockquote><p>Not to memorize IEEE-754. Not to fear floating-point numbers. Just to remove the mystery. And if you’ve followed the journey, I hope, that weirdness should be gone now.</p><p>Floating-point math didn’t betray intuition; it exposed where intuition quietly assumed exactness that never existed.</p><p>If you understood that, 0.1 + 0.2 no longer should feel weird, but boring.</p><p>That’s the whole point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1534a9ad973b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacky React: Refresher pattern]]></title>
            <link>https://blog.stackademic.com/hacky-react-refresher-pattern-8188f7f09eca?source=rss-585bf35838f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8188f7f09eca</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Igor Snitkin]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 18:21:09 GMT</pubDate>
            <atom:updated>2024-03-01T01:32:16.685Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey, dude 🖐 Today I feel naughty, let’s do some crazy s#!t with the React!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FUTFiHeDL8cOSA%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fthegoodfilms-vintage-cartoon-smiling-UTFiHeDL8cOSA&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExaHZyazByYTJxY2N0YWp3MWFtYWxsd24xbnI5Y3J1cWc5ZG10ODcwYiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FUTFiHeDL8cOSA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="317" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d88c0e7fd27a0963f93b634b8a0641c/href">https://medium.com/media/4d88c0e7fd27a0963f93b634b8a0641c/href</a></iframe><p>But wait… first, a quick disclaimer: like with any other hacky stuff, if something could be done, it doesn’t mean you need to go and do it. Common sense and a grain of salt shall be applied from this moment onwards.</p><p>We’ll start our journey the way any modern app’s journey should start:</p><blockquote>Hey GPT, generate the Quote of the Day React app. And be smart!</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09f56f29093003d99ab0807443769a83/href">https://medium.com/media/09f56f29093003d99ab0807443769a83/href</a></iframe><p>Tada 🎉 One shot one kill! Perfect code, and only a couple of minor misses: could have used .finally() for setting the loading state and unnecessary type union for the error variable. The rest is pretty much on point: we declare three stateful values, then use a side effect, and finally, return the HTML template.</p><p>So far, so good? OK! Let’s start hacking!</p><h3>Use effect?</h3><p>Interview time! Please tell me why we use theuseEffect hook in the code above. I bet your brain is mumbling something along the lines of:</p><blockquote>Fetch is a side effect we need to execute when the component is mounted, which is an important component’s lifecycle event. Furthermore, we need to make sure it happens only once, and hence we provide an empty array as the second argument to useEffect.</blockquote><p>Good job! Let’s draw a simple diagram of what’s happening:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*XK8G5mCTNlmD1QV3coBw1w.png" /><figcaption>Data fetching within a React component from useEffect hook</figcaption></figure><p>As you can see we run three miles for the meaningful data to appear on the screen. But isn’t it strange? Any experienced software engineer should ask themselves:</p><blockquote>Why TF are we running the first mile?? It makes no sense!</blockquote><p>Yeah, right? That was exactly my question too! It clearly should work like this, isn’t it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*BmvGM2X_s_levaBqzSWzNA.png" /><figcaption>Optimized data fetching pattern</figcaption></figure><p>So the first part of why we use the useEffect hook is rubbish and we don’t need it. What about the second part? We cannot just remove the hook, because we still need to fetch data once. A simple flag and we should be good:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1f92f57098765df9de277b0b84a5fff/href">https://medium.com/media/e1f92f57098765df9de277b0b84a5fff/href</a></iframe><p>Let’s see what we did: We extracted fetching logic away from the component and created the initialized flag just outside of the component* to make sure we fetch once.</p><p>*Important note: we’re able to extract the initialized variable into the outside scope of the component function because we’re pretty confident that QuoteOfTheDay will be used once. If that isn’t the case, then it immediately creates a problem as the initialized variable will be shared. So in cases, when components are reused you might want to create local references using <a href="https://react.dev/reference/react/useRef">React.useRef()</a>.</p><h3>Use state?</h3><p>Interview time! Please tell me why we use theuseState hook in the code above. I bet your brain is mumbling something along the lines of:</p><blockquote>The quote, isLoading and error are stateful variables and we need React to keep their current values in memory and a way to update them so React can re-render the component using new updated values.</blockquote><p>Good job! Let’s draw a simple diagram of what’s happening:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*SNfNSjk8LEhEJnpSzxj49g.png" /></figure><p>As you can see, once data is fetched, either way, we enqueue two setter tasks that React later will batch into a single re-render update. But isn’t it strange? Any experienced software engineer should ask themselves:</p><blockquote>Why TF can’t we merge tasks into a single setter task?</blockquote><p>Yeah, right? That was exactly my question too! It clearly should work like this, isn’t it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*FQeT8qjPA9YjOfm4rFMjcg.png" /></figure><p>Now, it might be not so obvious, but there are actually 3 different ways to solve this:</p><ol><li>Keep state in a single object, and update both values at the same time</li><li>Extract and use isLoading as an external reference, keeping quote and error as is</li><li>Extract and use quote and error as an external reference, only keeping isLoading as is</li></ol><p>If the first scenario is a good solution for you, feel free to stop reading this article — we won’t be able to optimize the code any further than this. A quick conclusion for you:</p><ul><li>Don’t wait until your component is mounted to fetch data</li><li>Batch state, so React doesn’t need to batch tasks</li></ul><p>Bye!</p><p>For those who stayed, let&#39;s hack on! 🤘🤘🤘</p><h3>Refresher pattern</h3><p>Question?! Do we set a new state to refresh the screen or to update a value? I’m asking this because as far as I am concerned, I can update any value synchronously and the state of my application in memory will indeed have an updated value. The problem, however, is that the state of my screen will be out of sync with the state in memory. So to me (which means in my personal opinion), it seems like the primary function of state setters is to let React know: “Hey, I’ve got new values. Let’s refresh the screen”.</p><p>If only I could keep the state out of my component and be able to mutate it synchronously, so I don’t have to use the Immer or any other immutability abstractions. And then, when I finish mutating a state, I could just ask React to re-render the component. Hmm… let’s think about the possible pros and cons of such a scenario:</p><h4>Pros:</h4><ul><li>The detached state will be easily transportable, think of a migration from React to any other framework; or migrating a state to the server instead 🚚</li><li>You don’t need to render a component to test a business logic 🧪</li><li>The React layer will become “dumber” with a very clear separation of concerns 👻</li><li>Things are likely to get ever so slightly faster 🏎️</li></ul><h4>Cons:</h4><ul><li>You will lose the “sync guarantee”: what you see on the screen isn’t necessarily what’s stored in memory: just think of the case when you mutate a state and forget to refresh the screen — a stale screen 💩</li><li>The shift of paradigm will likely require additional onboarding 📚</li></ul><p>And now, with all of the pros and cons in our minds, let’s do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cad9af1a1c0299b5a122d0080297f40/href">https://medium.com/media/1cad9af1a1c0299b5a122d0080297f40/href</a></iframe><h3>Conclusion</h3><blockquote>Hey GPT, read the article and generate the conclusion paragraph</blockquote><p>Chat GPT: <em>In conclusion, the Refresher pattern in React presents several distinct advantages, such as facilitating the portability of detached states and enabling seamless testing of business logic without component rendering. Additionally, it promotes a clearer separation of concerns within the React layer and may contribute to slight performance enhancements. However, it comes with drawbacks, notably the loss of the sync guarantee, potentially leading to discrepancies between the displayed content and the underlying state, as well as the need for additional onboarding to adapt to the paradigm shift. Despite these limitations, the Refresher pattern offers a valuable approach for managing state in React applications, especially when considering future scalability and maintainability.</em></p><p>Peace ✌️</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8188f7f09eca" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/hacky-react-refresher-pattern-8188f7f09eca">Hacky React: Refresher pattern</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID in React: the good, the bad, and the awesome]]></title>
            <link>https://itnext.io/solid-in-react-the-good-the-bad-and-the-awesome-79d6cc518d1f?source=rss-585bf35838f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/79d6cc518d1f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Igor Snitkin]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 11:51:14 GMT</pubDate>
            <atom:updated>2023-10-17T14:05:59.722Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s talk about SOLID principles from the perspective of the React application. If you’re not sure what SOLID principles are, you might want to read the following first:</p><ul><li><a href="https://medium.com/backticks-tildes/the-s-o-l-i-d-principles-in-pictures-b34ce2f1e898">The S.O.L.I.D Principles in Pictures</a></li><li><a href="https://medium.com/mindorks/solid-principles-explained-with-examples-79d1ce114ace">SOLID Principles — explained with examples</a></li></ul><p>I’m very well aware that there are plenty of articles on this exact topic already, and I know that because I’ve read most of them. And have to say I do disagree with the way the information is provided in those articles (otherwise I obviously wouldn’t have written this). The problem I see is that you’re only told how great and awesome SOLID principles are, without mentioning potential downsides or considerations; are they even applicable in React application? And that’s exactly what we’re going to discuss just now, so don’t stop reading!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fb3mSVYbDLvow8%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fclint-eastwood-eli-wallach-the-good-bad-and-ugly-b3mSVYbDLvow8&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMHY3NWZoMXpwNmZ3dTVqMnYxdGRrbmpvc3R0ejExbWdxMHZzZ3NvdyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fb3mSVYbDLvow8%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="187" frameborder="0" scrolling="no"><a href="https://medium.com/media/74e16b8d056aab0438412e79b62cf234/href">https://medium.com/media/74e16b8d056aab0438412e79b62cf234/href</a></iframe><h3>Chapter S: Single Responsibility Principle</h3><p>The very first principle is generally the easiest one to understand: your component should have a single responsibility, or in other words, <strong>there must be only one reason for this component to exist</strong>.</p><p>However, if you switch your brain from the consumption mode to thinking, you might immediately notice one problem: given that any non-leaf component in your application is the root of a subtree, there is an almost certain chance that some of your components will have more than one responsibility — the component has five children and controls the state of three of them. I bet your root App component violates the principle big time!</p><p>So what do we do? How do we navigate and apply the Single Responsibility Principle? If you look closely you are likely to find two groups of components: ones that are easy to design with the Single Responsibility Principle in mind; and others, some kind of orchestrators that have a lot of responsibility (or control). You can call them smart/dumb components, or container/presentational, I don’t really care as long as you acknowledge this separation.</p><p>I will call them <strong>managers</strong> and <strong>workers</strong>, and I claim that by introducing a simple set of rules you can make all the components of your application respect the Single Responsibility Principle! Let’s define them:</p><ol><li>Managers should never do Workers’ jobs, in other words, their single responsibility is managing and composing Workers (or other Managers).</li><li>Workers should not be aware of business logic and should never delegate jobs to Managers, only to other Workers.</li></ol><p>Let’s think about those two rules for a second. What does “Managers should never do Workers’ jobs” even mean? It means that Managers should never have their own JSX content, whatever they return should only consist of Workers and/or other Managers, or to put it super simply, they should not have their own HTML elements. As a result, they also won’t have CSS, as there will be nothing to style. You can safely say that Managers represent the (java)script part of your application — they carry all the business logic and control most user interactions.</p><p>What about Workers who “should not be aware of business logic”? Well, that would be the opposite! They will carry all the content and styling (or HTML and CSS part of your application), with little to no JavaScript — only required for their own isolated existence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*1wzefSPDPFpne7k-rJLT7A.jpeg" /></figure><p>I have to note that there is a pretty big caveat when it comes to styling (way too big to include it here), and depending on when you’re reading this, there might or might not be another article from me titled “How styling destroys your React app” (or something like that).</p><p>Also note, that the fact that Workers cannot delegate jobs to Managers doesn’t mean Managers cannot be children of Workers in your component tree, and we’ll talk about it in the last chapter 😉</p><h3>Chapter O: Open/Closed Principle</h3><p>This principle has an easy-sounding definition: <strong>your component should be open for extensions and closed for modifications</strong>, and yet it might not be as easy to understand the difference between an extension and modification. From the point of view of the component itself, any extension is a modification. Therefore we can deduct that this principle relies purely on the point of view of the external consumer of your component:</p><blockquote>“I don’t care what you do to your component as long as it doesn’t require me to change the way I use it!”</blockquote><p>This might sound familiar! That’s because this principle is the backbone of <a href="https://en.wikipedia.org/wiki/Backward_compatibility">Backward compatibility</a>, and it’s literally everywhere. Web APIs and design trends will always evolve and you should always expect a need for the evolution of your components, and this evolution should always* respect existing consumers. Let’s see the Open/Closed Principle in practice with a simple example:</p><p>You were tasked with creating a Button component that will, if provided, display an icon, and so you did it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b2598181c64b80f13d859f0eb8b748a/href">https://medium.com/media/2b2598181c64b80f13d859f0eb8b748a/href</a></iframe><p>Sometime later, the product designer tells you: <em>“Dude, we need a button with the icon on the right side!”</em>, what are your actions? Try to pause and think about what would you do.</p><p>There is more than one way to achieve this new behavior, for example by introducing a new prop iconPlacement with the default value of left/start, which will control the icon’s position. As long as consumers are happy I wouldn’t argue against this, but personally, I would actually introduce two new props and deprecate one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdf005fdcf8e891ef7dda085caed7446/href">https://medium.com/media/cdf005fdcf8e891ef7dda085caed7446/href</a></iframe><p>I hope this clears a little bit on what is the Open/Closed Principle and how to implement it in your React application. Note, that this principle is not a silver bullet (HINT: nothing is) and extensions inevitably lead to BIG(ger) files and at some point become counterproductive. Sometimes you might want to go the route of extending the components and creating their subtypes instead:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/258288905a89591b6d683fdd3e2fa8cf/href">https://medium.com/media/258288905a89591b6d683fdd3e2fa8cf/href</a></iframe><p>Can you spot a potential problem in this component? Don’t worry if not — we will talk about it in the next chapter.</p><h3>Chapter L: Liskov Substitution Principle</h3><p>The Liskov Substitution Principle is based on covariance: <strong>you should be able to substitute any supertype with its subtype</strong>. For those who didn’t take computer science classes in school, the naming might sound a bit weird. If I extend a type A creating new type B, it is counterintuitive to call type B a subtype of A and A a supertype of B, but that’s what it is — remember, trees in computer science grow down too.</p><p>So what mistake did I make in the IconButton component above? IconButton extends theButton component, in other words, is a subcomponent of theButton. Now, I have two questions for you, the first one you might have already guessed, and the second is a tricky one:</p><ol><li>Can I substitute all occurrences of theButton component with its subtype component, IconButton?</li><li>Would it be reasonable to do this substitution in the first place?</li></ol><p>The answer to the first question is NO! By omitting the icon property of the Button component I effectively violated the Liskov Substitution Principle. My IconButton component is rather an “orphan child”, and not a classic subtype of the Button. Both types are independent and non-substitutable or, using fancy technical jargon, are invariants of each other.</p><p>The answer to the second question is <strong>also </strong>NO! Because it was never my intention to create a subtype in the first place, or in other words, the IconButton was never meant to substitute the Button.</p><p>This is a great example of Composition vs. Inheritance in programming: the Liskov Substitution Principle is based on Inheritance and React is on Composition (we’ll see it later). The fact that React is based on composition doesn’t mean, however, that there is no place for inheritance. In fact, if you have a look at the Button component above, I intentionally made it a subtype of HTMLButtonElement by enabling two crucial functionalities:</p><ul><li><strong>extends React.PropsWithChildren</strong>: it accepts content</li><li><strong>extends React.HTMLAttributes&lt;HTMLButtonElement&gt;</strong>: it accepts attributes</li></ul><p>As Button component respects the Liskov Substitution Principle**, I can just go and safely substitute all occurrences of button HTML element with it in my application, and that was exactly the plan.</p><p>So why not making IconButton respect the Liskov Substitution Principle, you might ask. It is certainly possible, but very soon your code will turn into a hot mess with unnecessarily convoluted components and a whole list of things that can introduce a lot of drama in your life.</p><p>If you’re someone in the early stages of developing React apps, I would just advise you to ignore the principle. If you feel comfortable with React, you should always start with the question: <em>Is this component meant to substitute the base component or element it extends?</em> If yes, make sure you respect the Liskov Substitution Principle, by properly forwarding props, children, attributes, and ref. If not, however — don’t do it!</p><h3>Chapter I: Interface Segregation Principle</h3><p>If I ever need to choose one of the SOLID principles you can blindly follow, no questions asked, that surely would be the Interface Segregation Principle: <strong>a component should not depend on properties it doesn’t use</strong>.</p><p>At first, this principle might seem strangely simple: why would anyone introduce props the component doesn’t use? If we use proper linter configuration we won’t be even able to do that on purpose, right? What’s the catch?</p><p>The catch is the recursive nature of this principle, consider the following component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bd36174ba4419aebac154a961e9d8cd/href">https://medium.com/media/8bd36174ba4419aebac154a961e9d8cd/href</a></iframe><p>At first, it seems like there are no unused props here, we do use user and that’s the only prop we have. However, <strong>recursively</strong>, the User type drags a bunch of unused properties, like email and id, to name a few, into our component — something that this component absolutely doesn’t need and that’s where the Interface Segregation Principle is violated. It is closely related to our discussion about Worker components above, that they shouldn’t be aware of business logic. In fact, one can argue that they should not be aware of anything external at all (not always possible).</p><p>Let’s fix it!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c12aaccf0cf1591ec07175223bd2c9a/href">https://medium.com/media/2c12aaccf0cf1591ec07175223bd2c9a/href</a></iframe><p>Let’s analyze what has changed. The most important thing that we did was remove the import on <a href="https://gist.github.com/snigo/ad12ea0bc9969152ce383b6cdb150258#file-solid_react-004-useravatarbad-tsx-L3">line 3</a> in the first example. By doing this we effectively decoupled UserAvatar from the User interface, which in turn greatly enhanced the reusability of our component. In fact, we even removed any mention of “User” from the naming — now our pets can have avatars too! 😻</p><h3>Chapter D: Dependency Inversion Principle</h3><p>And now, for our final chapter, please welcome the one and only, the Godfather of composition in React, the principle of all principles — the Dependency Inversion Principle! The official definition is somewhat hard to understand, especially at first sight; it’s also the only SOLID principle that has a two-part definition:</p><blockquote>A. High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).<br>B. Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.</blockquote><p>If it sounds heavy, that’s because it is. The Dependency Inversion Principle, as you might have noted by my glorious introduction, easily deserves an article of its own. And when it comes to React, I have good news and bad news for you:</p><p>GOOD: <strong>You are using the Dependency Inversion Principle by default</strong> without even noticing it!</p><p>BAD: You are using the Dependency Inversion Principle <strong>by default without even noticing it</strong>!</p><p>So, let’s unpack it and start noticing this by far the most powerful SOLID principle that is the foundation of all things React. Let’s start with parsing the name: what is the dependency? It is an external code (module, package, function, hook, component, etc.) that I use in my component. There are exactly <strong>two</strong> ways this dependency can appear “on my territory”:</p><ol><li><strong>Import</strong>: I import it from its corresponding module</li><li><strong>Injection</strong>: it’s passed to me as a parameter (or prop)</li></ol><p>Import is a <strong>direct dependency</strong>, which I have little to no control over. If that dependency changes its behavior I’m screwed.</p><p>Injection is an <strong>inverse dependency: </strong>even though I depend on what’s passed to me, I control what can be passed with an abstraction — the props interface.</p><p>Note, how closely intertwined the Dependency Inversion Principle is with the Single Responsibility Principle and the Interface Segregation Principle. Remember, in our badUserAvatar example above we mentioned that the component shouldn’t be aware of business logic (be a Worker); also that we shouldn’t pass properties/information component doesn’t need; the Dependency Inversion Principle adds the third reason why that component is bad — we’re creating a direct dependency, or in other words, our abstraction (AvatarProps) depends on details (User).</p><p>The second and most important thing you have to note is that the Dependency Inversion doesn’t stop just on passing functions in our components. Literally, every example out there about this principle in React talks exclusively about event handlers, not noticing the most important thing the Dependency Inversion Principle enables. Let’s rewrite our Button component again and see if you can notice it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5057ae4fdc9a18288ab4846f5207879a/href">https://medium.com/media/5057ae4fdc9a18288ab4846f5207879a/href</a></iframe><p>So, onClick is the obvious one: it cannot be baked in, otherwise it will violate the Single Responsibility Principle, and it cannot be directly imported as it will violate the Dependency Inversion Principle. Do you see any other examples of dependency injection here? What about children? Are they passed as a prop? Check! Do I control their type? Check! And here is the culmination of this chapter:</p><blockquote>Whenever you talk about the Composition Pattern in React you talk about the Dependency Inversion Principle. They are the same!</blockquote><p>This is exactly what makes it possible for Workers from the first chapter to be higher in the component tree compared to Managers — their dependency is inversed and they effectively become containers*** without being aware of what exactly they contain, and hence not violating the Single Responsibility Principle.</p><p>Now, let’s get back to my promise from Chapter L to show you that <em>everything</em> in React is a composition. The way we pass children in React is nothing else than <a href="https://en.wikipedia.org/wiki/Syntactic_sugar">syntactic sugar</a>. Look closely at these components and the way they are used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5161a036bf9d4e117f420a6108f2918/href">https://medium.com/media/b5161a036bf9d4e117f420a6108f2918/href</a></iframe><p>Components A and B are identical, with the only difference: I’m able to pass data to the component in a more natural (from the JSX’s point of view) way by using reserved children prop.</p><p>Now, let’s talk about type discrimination. The type ReactNode | undefined is not a law per se, it’s just the most generic type React is able to work with without crashing. But we’re free to govern the type, remember? So, let’s narrow our types and rewrite the sections above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31ab892d51261e9ebb5d52f6c31bbf48/href">https://medium.com/media/31ab892d51261e9ebb5d52f6c31bbf48/href</a></iframe><p>As you can see, the composition in React isn&#39;t reserved just for children prop, you can compose your application with any prop name; it isn’t reserved just for ReactNode type, you can compose your application with any prop type. Everything in React is a composition.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSTUAgwgXPdZDO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fminecraft-STUAgwgXPdZDO&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExM3gyNnluemk4MW13eG9hMjFpc2pqeDU2cmM1YWFpdWVsdzExcHp5YyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FSTUAgwgXPdZDO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="242" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c5ed6466762e6ecad69762c9796daa2/href">https://medium.com/media/3c5ed6466762e6ecad69762c9796daa2/href</a></iframe><p>Purely from React’s point of view, the Dependency Inversion Principle is nothing else than lifting responsibility up to the parent. This makes total sense considering the Manager/Worker pattern we discussed in the first chapter. But, just like with the Single Responsibility Principle, if you switch your brain from consumption to thinking one last time, you will notice quite a big problem again. You cannot just lift the responsibility up indefinitely. In other words, your application will need at least one Manager component; and if it’s only one, just like in real life, you can imagine the level and the amount of responsibility this poor guy will have. This will absolutely result in a disaster from the readability and reasoning point of view.</p><p>Despite all the incredible advantages and the stability the Dependency Inversion Principle gives you by decoupling your components, the composition has to stop at certain levels, and Manager components seem like a great place to do that. It is generally a good idea, however, to follow the Dependency Inversion Principle as much as possible, or in other words to keep the number of Manager components in your application as low as possible, and only break the functionality when Managers become overloaded. For example, if you start a new Next.js project, you naturally will have two managers per route, layout.tsx and page.tsx. Later, if your page has a lot of features, you can lighten up page.tsx by introducing a manager component for each feature and so on.</p><p>OK, and that’s a wrap! Luckily for me, there are no more letters in SOLID and I can finally stop this long and painful process of writing this article. My overall conclusion is that despite its roots in Object-Oriented Programming, SOLID principles are very well applicable in React app development, so there is definitely value in knowing them, particularly, in recognizing that a lot of code that we write by default without thinking too much is actually based on these fundamentals.</p><p>I really hope it will clear things up a little bit for you, and if it will, I would appreciate it if you share this with the world somehow.</p><h4>Footnotes</h4><ul><li>* The component evolution should not <em>always</em> respect the consumer. The general approach is to group your components into a library with version control, which in turn allows the introduction of breaking changes.</li><li>** This is an intentional oversimplification for demonstration purposes only. The proper solution would have to forward ref and stop overriding the className</li><li>***This is the reason I prefer manager/worker naming over the presentational/container popularized by Dan Abramov. “To contain” not necessarily mean “to control”.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79d6cc518d1f" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/solid-in-react-the-good-the-bad-and-the-awesome-79d6cc518d1f">SOLID in React: the good, the bad, and the awesome</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useEffect or not useEffect?]]></title>
            <link>https://snigo.medium.com/useeffect-or-not-useeffect-35c059b41f84?source=rss-585bf35838f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/35c059b41f84</guid>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Igor Snitkin]]></dc:creator>
            <pubDate>Sat, 24 Sep 2022 22:22:25 GMT</pubDate>
            <atom:updated>2022-09-24T22:22:25.629Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I started noticing a new trend online — everyone seemed to trash talk useEffect hook from the notorious React library. It didn’t take very long to find a source for this behavior, a very comprehensive <a href="https://beta.reactjs.org/learn/you-might-not-need-an-effect"><em>You Might Not Need an Effect</em> article on React Docs</a>.</p><p>As we, in my team, use this hook considerably often this meant just one thing and one thing only — it’s time to wear my lab coverall and do some research, hopefully, busting some myths along the way! It’s rock’n’roll, baby!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Hh8PC6fv2wgM4wAWgoVBYQ.gif" /><figcaption>Source: GIPHY</figcaption></figure><h3>TLDR;</h3><p>So the main problem with useEffect hook is that it executes provided callback <strong>only</strong> after all updates to the DOM are made. In other words, if your useEffect hook updates a state according to some condition, you will render the component, do all required updates to the DOM, still with the previous state, and only then you will trigger the re-render of the component with the next state.</p><p>On another hand, without useEffect, whenever React will detect an update of the state during the render, it will immediately toss the output of this render and will start a new render with the new state right away, without making any updates to the DOM, which are the most expensive part of the equation.</p><h3>Updating state based on state</h3><p>Verdict: CONFIRMED!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/503ab12e2117c5b2ff1fe7d4bef211d1/href">https://medium.com/media/503ab12e2117c5b2ff1fe7d4bef211d1/href</a></iframe><p>This is a pretty easy and highly unlikely one — searching through our codebase, I couldn’t find any actual case of such use. Any value derived from a state we would call a derived state and this value should <strong>not</strong> be stateful. Not hard to remember.</p><p>As the article suggests, you should calculate the derived state directly during the rendering or, if it involves some complex computation, use useMemo hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eff0ca6f0ac30a8d2e11b6685046d96a/href">https://medium.com/media/eff0ca6f0ac30a8d2e11b6685046d96a/href</a></iframe><h3>Updating state based on props</h3><p>Updating the state based on provided props frankly speaking just sucks, or shall I say smells! If possible this should be avoided at all costs by lifting the state up. If you ever used git and had to resolve conflicts, try to think why on Earth I just mentioned this 🙃</p><p>Let’s consider three possible scenarios when props affect the state</p><h4>State supersedes props</h4><p>Verdict: CONFIRMED!</p><p>In a naive world, this would be as easy as this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53f83f630360687d2f4a42fcc2659949/href">https://medium.com/media/53f83f630360687d2f4a42fcc2659949/href</a></iframe><p>People who worked with real-life applications will immediately notice a problem — chances are defaultValue from the code above won’t be accessible synchronously during the <em>constructor</em> time, either because it comes from some kind of subscription, like React Context, or is an asynchronous stateful value by itself. In this case, we need something a bit smarter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/035981e27964c7f77465a7c932e8a87d/href">https://medium.com/media/035981e27964c7f77465a7c932e8a87d/href</a></iframe><p>So why are we updating the state early, during the render, and not inside an effect? Because in this case, React <strong>will not make any changes to the DOM</strong> and will directly proceed with re-rendering the component, unlike when the update is initiated inside of the useEffect hook.</p><p>If you or people reviewing your code are freaked out a little by the code above, remember, that you can always abstract hook by custom hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09efc03a003cde0828f2af549bb65053/href">https://medium.com/media/09efc03a003cde0828f2af549bb65053/href</a></iframe><h4>Props supersede state aka Resetting the state</h4><p>Verdict: CONFIRMED + BUSTED!</p><p><strong>Disclaimer:</strong> It’s busted not because you have to use an effect, but because of the suggested in the article approach.</p><p>In our codebase, we reset the state based on props in many places, but all of the cases have the same pattern — we have some modal surface, like a dialog window or sidebar, that is always rendered and whose visibility is toggled by open prop. Sounds familiar? Sometimes we need to reset the internal state of this element whenever it’s open. The question is, how do you do that?</p><p>React team proposes changing a key of the component every time you need to reset a state and at first, it seemed like a genius idea:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/427e236be8cfd71bd2612084f11516ba/href">https://medium.com/media/427e236be8cfd71bd2612084f11516ba/href</a></iframe><p>This totally works, the state is re-instated every time dialogOpen changes, exactly what we wanted, right? Yeah, but at what cost?</p><p>First of all, we completely re-mount the whole subtree which defies the purpose the open prop was used for in the first place, secondly, we do it not only when the dialog is open, but also when it’s closed — we re-mount something that is not even visible on the screen. Not good!</p><p>Let’s see if we can improve this. Remember from the last example: the goal is to update the state early, during the render. We again will be using a stable reference to remember the previous state of the dialog window:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50d58364f6701127f5112842ab322ff4/href">https://medium.com/media/50d58364f6701127f5112842ab322ff4/href</a></iframe><h4>State and Props merge</h4><p>Verdict: CONFIRMED!</p><p>By now, I’m sure you have a very solid understanding of how to avoid useEffect and update the state earlier by keeping some references to the previous values or state. Just for demonstration purposes, I’ll give you another approach to this scenario using the derived state method we discussed earlier, which works perfectly when you need to merge state and props together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/debf85951d3669bdfb62183a3ac2e733/href">https://medium.com/media/debf85951d3669bdfb62183a3ac2e733/href</a></iframe><h3>Words of caution</h3><p>While playing with this and trying to remove useEffect hook from various places in our codebase I found a couple of scenarios where it’s either impossible or not that straightforward to remove it:</p><ol><li>You need to be extra cautious with functions aka callbacks passed as props to your component, as it’s very tempting to call those using the same principle — before any updates to the DOM are made. The problem arises when and if those callbacks will unmount your component because your component is only scheduled to appear in the DOM at this stage. So any such callbacks that will unmount the component have to be called inside the useEffect.</li><li>Considering our example on top, using the stateInitialized reference, if your defaultValue will appear a little too fast you most likely will run into race conditions in React’s strict mode. The good news — it will work just fine in production, the bad news — it’s super trippy and very unpleasant.</li><li>useEffect comes with a very convenient way to conditionally invoke the provided callback only when any of the values in the dependency array changes. On top of that, you have an exhaustive-deps ESLint rule guarding any potential fuckups. Without useEffect you’re on your own and the chances to create a stale state or blow up your stack by an infinite re-renders increase.</li></ol><h3>Conclusion</h3><p>Aside from a little blunder with suggesting to update keys of the components to reset their state, I didn’t really bust anything — React team knows what they’re talking about, no surprises here. And yes! You and I and we’re all overusing useEffect and there is a very big chance you indeed might not need it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35c059b41f84" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>