<?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 Sudeep Gumaste on Medium]]></title>
        <description><![CDATA[Stories by Sudeep Gumaste on Medium]]></description>
        <link>https://medium.com/@so_deep.dev?source=rss-c585f7ee303d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9u2pRwkofGd_yBZthLM7Sg.jpeg</url>
            <title>Stories by Sudeep Gumaste on Medium</title>
            <link>https://medium.com/@so_deep.dev?source=rss-c585f7ee303d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 01:29:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@so_deep.dev/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[Maybe I’ll Understand Legend-State If I Build It, Part 5: It Peaked at One Level]]></title>
            <link>https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-5-it-peaked-at-one-level-77c3525591e8?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/77c3525591e8</guid>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 14:48:22 GMT</pubDate>
            <atom:updated>2026-11-02T14:48:22.674Z</atom:updated>
            <content:encoded><![CDATA[<p>Four parts in, we have a reactive core that batches its writes, cleans up after itself, and drives React through a hook. It also has a ceiling we’ve been quietly living under the whole time: everything is one level deep. job$.status works. job$.attachments.doc.name does not. Real state nests, and ours flatly refuses to.</p><p>This is the part where it goes deep. The whole trick is one word, recursive, and by the end every level of an observable will be its own node, all the way down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6uwB3z-7hQ6Xw95XC--fQ.png" /></figure><h3>Where it dead-ends</h3><p>Here’s the node factory from the earlier parts, trimmed to the shape that matters:</p><pre>const node = (key: string): Node&lt;unknown&gt; =&gt; ({<br>  get() { /* subscribe the reader, then */ return store[key] },<br>  set(value) { /* write, then notify */ },<br>})<br><br>const proxy = new Proxy(store, {<br>  get(_store, key: string) { return node(key) },<br>})</pre><p>Reach for a key and you get a node, a plain object with get and set. That&#39;s the door from Part 1. The problem is the node is where the road ends. job$.attachments returns a node, and a node has get and set and nothing else, so job$.attachments.doc is undefined.</p><pre>job$.attachments.get()      // { doc: {...}, image: {...} }   fine<br>job$.attachments.doc        // undefined   the node has no .doc<br>job$.attachments.doc.name   // TypeError: reading &#39;name&#39; of undefined</pre><p>You can read the whole attachments object and pick through it by hand, but the moment you do, you&#39;ve left the reactive world. job$.attachments.get().doc.name reads a plain string off a plain object. Nothing is tracking it. Set it and no one hears.</p><p>So one level of nodes isn’t enough. We need a node at every level.</p><h3>Every level is a node</h3><p>Picture what we want. job$ is a node. job$.attachments is a node. job$.attachments.doc is a node. job$.attachments.doc.name is a node. Each one has .get() and .set(), and each one also lets you go one level deeper.</p><p>That’s the tension to solve. A node has to be two things at once: a value door, with get and set, and a way to descend, so .doc on a node hands back another node. A plain { get, set } object can only ever be the first. To be both, the node has to be a proxy.</p><h3>The recursive proxy</h3><p>Here’s the rewrite, let’s look at the shape of the change. The flat version kept one map from a top-level key to its readers, and handed back a plain { get, set } object that could only ever stand for that one key. Going deep forces two of those decisions to change.</p><p>Subscriptions move from a single key to a full path. A reader can attach at any depth now, so a subscription is identified by its whole path, &#39;attachments.doc.name&#39;, and get and set walk that path into the store instead of indexing one key. So subscribers becomes a map from a path string to a set of readers.</p><p>The type is the same either way, Map&lt;string, Set&lt;Observer&gt;&gt;. What changes is what the keys mean. Flat, they were bare top-level names, and attachments was as deep as a key could go:</p><pre>Map {<br>  &#39;status&#39;      =&gt; Set(readers),<br>  &#39;attachments&#39; =&gt; Set(readers),<br>}</pre><p>Now every path a reader actually touches gets its own entry, however deep:</p><pre>Map {<br>  &#39;status&#39;                 =&gt; Set(readers),<br>  &#39;attachments.doc.name&#39;   =&gt; Set(readers),<br>  &#39;attachments.image.name&#39; =&gt; Set(readers),<br>}</pre><p>The node also stops being a plain object and becomes a proxy. A plain { get, set } can answer those two keys and nothing else, which is exactly why the flat version dead-ended. A proxy can answer get and set with the value doors, and answer any other key by handing back another node one level deeper. That last fallthrough is the recursion.</p><p>Build it a piece at a time. It all lives in a node(path) factory that returns a proxy, with the path&#39;s dotted string as the subscription key. The get trap handles three cases: the two reserved doors, get and set, which we will fill in shortly, and the descend that gets you to them.</p><pre>const node = (path: string[]): any =&gt; {<br>  const key = path.join(&#39;.&#39;) // keeps collecting the entire path<br><br>  return new Proxy({}, {<br>    get(_target, prop: string) {<br>      if (prop === &#39;get&#39;) {<br>        // the reader door function, coming up...<br>      }<br><br>      if (prop === &#39;set&#39;) {<br>        // the writer door function, coming up...<br>      }<br><br>      return node([...path, prop]) // which is again a proxy with get trap<br>    },<br>  })<br>}</pre><p>Starting with that last line, the walking a level deeper (or the descend), because it’s what makes the whole thing a tree. Every dot in job$.attachments.doc.name is a property read, and each one fires this trap on the node it&#39;s read from. Most of those reads aren&#39;t get or set, they&#39;re keys like attachments and doc, and each one falls through to return node([...path, prop]), a child node one level deeper, with the key appended to the path. That is the recursion. You never reach into the store directly, you walk a chain of nodes, one trap call per dot.</p><p>Follow one deep read and watch the path assemble, job$.attachments.doc.name.get():</p><pre>job$                 // node([]), the root node<br>  .attachments       // descend -&gt; node([&#39;attachments&#39;])<br>  .doc               // descend -&gt; node([&#39;attachments&#39;, &#39;doc&#39;])<br>  .name              // descend -&gt; node([&#39;attachments&#39;, &#39;doc&#39;, &#39;name&#39;])<br>  .get               // reserved: returns the reader for that path<br>  ()                 // runs the reader: subscribe, then read the value</pre><p>If you remember from the <a href="https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-1-it-starts-with-a-proxy-2d5123399217">1st article</a>, whenever you try to access a property on a proxy, the get trap fires. Every one of those dots is a read, which causes the firing of the get trap, .get and .set included. What differs is the branch the trap takes. For attachments, doc, and name, the property name isn&#39;t a reserved word, so each falls through to the descend branch, growing path by one key via [...path, prop]. For .get, the property name is the string &#39;get&#39;, so the if (prop === &#39;get&#39;) branch runs and hands back the reader function instead of descending. The final () then runs that reader, the only step that touches the store, and the only one that subscribes.</p><p>The nodes are made on the way down when they are accessed, they are transient. We never walk the tree to wrap it. A node for attachments.doc.name comes into being only when someone reaches for that path, and it&#39;s gone again as soon as it falls out of scope. That&#39;s how a store with a big, deep shape stays cheap, it costs only for the paths you actually touch.</p><p>Now let’s talk about the get and set methods that we decided to look at shortly. The first is reading. Ask a node for get and you get the reader function. It subscribes the current reader to this path, then walks the path into the store and returns the value.</p><pre>if (prop === &#39;get&#39;)<br>  return () =&gt; {<br>    const observer = currentObserver()<br>    if (observer) {<br>      const subs = subsFor(key)<br>      subs.add(observer)<br>      observer.deps.add(subs)<br>    }<br>    return path.reduce((value, k) =&gt; value[k], store)<br>  }</pre><p>path.reduce((value, k) =&gt; value[k], store) is store.attachments.doc.name spelled as a loop. The subscribe step is exactly the flat version&#39;s, except the key it subscribes under is now a path.</p><p>The second is writing. Ask for set and you get the writer door: it walks to the parent, assigns the new value, and notifies. The beginBatch/endBatch wrapper is unchanged, so a lone write is still a batch of one and computeds still stay fresh mid-batch.</p><pre>if (prop === &#39;set&#39;)<br>  return (value: unknown) =&gt; {<br>    beginBatch()<br>    try {<br>      const parent = path.slice(0, -1).reduce((v, k) =&gt; v[k], store)<br>      parent[path[path.length - 1]] = value<br>      // the notify loop<br>      for (const [p, subs] of subscribers)<br>        if (p === key || p.startsWith(key + &#39;.&#39;)) notify(subs)<br>    } finally {<br>      endBatch()<br>    }<br>  }</pre><p>That notify loop is the a new piece, and it has a section of its own just below.</p><p>Lookin at who ends up registered where. Each reader lands in a single set, the one for the exact path it read: a component reading job$.attachments.doc.name registers under &#39;attachments.doc.name&#39; and that key alone. Only the final .get() subscribes. The attachments and attachments.doc it passed through were descents that returned deeper nodes, so they hold no readers and aren&#39;t even keys in the map.</p><p>Now everything assembled together:</p><pre>function observable&lt;T&gt;(initial: T): Observable&lt;T&gt; {<br>  const store = initial as any<br>  const subscribers = new Map&lt;string, Set&lt;Observer&gt;&gt;()<br><br>  const subsFor = (path: string) =&gt; {<br>    let subs = subscribers.get(path)<br>    if (!subs) subscribers.set(path, (subs = new Set()))<br>    return subs<br>  }<br><br>  const node = (path: string[]): any =&gt; {<br>    const key = path.join(&#39;.&#39;) // &#39;attachments.doc.name&#39;<br><br>    return new Proxy({}, {<br>      get(_target, prop: string) {<br>        if (prop === &#39;get&#39;)<br>          return () =&gt; {<br>            const observer = currentObserver()<br>            if (observer) {<br>              const subs = subsFor(key)<br>              subs.add(observer)<br>              observer.deps.add(subs)<br>            }<br>            return path.reduce((value, k) =&gt; value[k], store)<br>          }<br><br>        if (prop === &#39;set&#39;)<br>          return (value: unknown) =&gt; {<br>            beginBatch()<br>            try {<br>              const parent = path.slice(0, -1).reduce((v, k) =&gt; v[k], store)<br>              parent[path[path.length - 1]] = value<br>              for (const [p, subs] of subscribers)<br>                if (p === key || p.startsWith(key + &#39;.&#39;)) notify(subs)<br>            } finally {<br>              endBatch()<br>            }<br>          }<br><br>        return node([...path, prop]) // any other key: descend a level<br>      },<br>    })<br>  }<br><br>  return node([])<br>}</pre><h3>Notifying a subtree</h3><p>In the flat world, a write touched one key and woke that key’s readers. Done. With nesting, a write can land at any depth, and it can matter to readers sitting below where it lands.</p><p>Consider this example where deeper readers exist and a top level value is replaced. Say a component reads job$.attachments.doc.name, and elsewhere the whole document gets swapped out:</p><pre>job$.attachments.doc.set({<br>  name: &#39;v2.pdf&#39;,<br>  link: &#39;/files/v2.pdf&#39;,<br>  mimetype: &#39;application/pdf&#39;,<br>})</pre><p>Picture the subscriber map when that write lands, with a few components reading different leaves:</p><pre>Map {<br>  &#39;status&#39;                 =&gt; Set(readers),<br>  &#39;attachments.doc.name&#39;   =&gt; Set(readers),<br>  &#39;attachments.doc.link&#39;   =&gt; Set(readers),<br>  &#39;attachments.image.name&#39; =&gt; Set(readers),<br>}</pre><p>The write’s key is &#39;attachments.doc&#39;, but the reader we care about is watching &#39;attachments.doc.name&#39;, a path underneath it. Its value just changed, so it has to be told. That&#39;s why the notify loop matches two things:</p><pre>for (const [p, subs] of subscribers)<br>  if (p === key || p.startsWith(key + &#39;.&#39;)) notify(subs)</pre><p>p === key is the exact hit. p.startsWith(key + &#39;.&#39;) is every path beneath the one we wrote. Run it against the map above with key = &#39;attachments.doc&#39;: &#39;attachments.doc.name&#39; and &#39;attachments.doc.link&#39; both start with &#39;attachments.doc.&#39;, so both get notified, while &#39;attachments.image.name&#39; and &#39;status&#39; match neither test and stay asleep. Replacing a subtree reaches every leaf under it, and nothing else.</p><p>Fine-grained tracking survives this. Writing attachments.doc.name doesn&#39;t match attachments.image.name, since neither path is a prefix of the other, so a component reading the image name never re-renders when the doc name changes. Subtree-wide notification when you replace a subtree, pinpoint notification when you set a leaf, both fall out of the same two-line check.</p><p>That settles where a change is felt. It leaves one more question, when a write counts as a change at all, which is the next thing to pin down.</p><h3>When a write counts as a change</h3><p>set currently writes and notifies every time, whether or not anything actually changed. Setting a field to the value it already holds wakes its readers for nothing. So does replacing an object with a fresh copy of the same contents. Our reader-side Object.is quietly absorbs the first case for primitives, but a new object with identical contents has a different reference, so it sails through and re-renders anyway.</p><p>The fix is to decide at the source, by value. Before writing, check whether the new value deeply equals the current one, and if it does, do nothing:</p><pre>if (prop === &#39;set&#39;)<br>  return (value: unknown) =&gt; {<br>    const current = path.reduce((v, k) =&gt; v[k], store)<br>    if (deepEqual(current, value)) return // nothing actually changed<br>    beginBatch()<br>    try {<br>      const parent = path.slice(0, -1).reduce((v, k) =&gt; v[k], store)<br>      parent[path[path.length - 1]] = value<br>      for (const [p, subs] of subscribers)<br>        if (p === key || p.startsWith(key + &#39;.&#39;)) notify(subs)<br>    } finally {<br>      endBatch()<br>    }<br>  }</pre><p>with a compact deepEqual:</p><pre>function deepEqual(a: unknown, b: unknown): boolean {<br>  if (Object.is(a, b)) return true<br>  if (typeof a !== &#39;object&#39; || typeof b !== &#39;object&#39; || a === null || b === null)<br>    return false<br>  const ao = a as Record&lt;string, unknown&gt;<br>  const bo = b as Record&lt;string, unknown&gt;<br>  const ka = Object.keys(ao)<br>  const kb = Object.keys(bo)<br>  return ka.length === kb.length &amp;&amp; ka.every((k) =&gt; deepEqual(ao[k], bo[k]))<br>}</pre><p>Now a no-op write reaches no one: a primitive set to the value it already has, or an object replaced by a deep copy of itself, notifies nothing. This is the change-detection model Legend leans on, and it’s what lets a signal library sit on plain, mutable data instead of demanding a new reference for every change. You decide something changed by comparing values, not pointers. A production deepEqual also handles arrays, Maps, Dates, and cycles; this one covers plain objects and primitives, which is enough to make the point.</p><h3>The type, recursively</h3><p>The runtime is recursive, so the type follows. In Part 1, Observable&lt;T&gt; mapped each key to a Node. Now each key maps to another Observable, and the nesting continues in the type exactly as far as it does in the data:</p><pre>type Node&lt;V&gt; = {<br>  get(): V<br>  set(value: V): void<br>}<br><br>type Observable&lt;T&gt; = Node&lt;T&gt; &amp;<br>  (T extends object ? { [K in keyof T]: Observable&lt;T[K]&gt; } : unknown)</pre><p>Observable&lt;{ status: string }&gt; is a node for the whole object, plus a status that is itself an Observable&lt;string&gt;, which is just a Node&lt;string&gt;. So job$.attachments.doc.name types as Node&lt;string&gt;, .get() returns a string, and autocomplete follows you the whole way down.</p><h3>Reading without subscribing: peek()</h3><p>Sometimes you want the value without the subscription. Inside an event handler, or when you’re reading a value only to pass it along, going through get() would quietly subscribe whatever reader happens to be on the stack. Legend&#39;s answer is peek(), a read that skips tracking. It&#39;s a third door on the node, and it&#39;s the get() door with the subscribe step removed:</p><pre>if (prop === &#39;peek&#39;)<br>  return () =&gt; path.reduce((value, k) =&gt; value[k], store)</pre><p>get() subscribes and then reads. peek() just reads. Add peek(): V to the Node type next to get and set, and every level has it, same as everything else.</p><h3>Runtime caveats</h3><p>The proxy answers to any key by handing back a child node. That’s the whole idea for your data, but the runtime pokes at objects with keys you never put there, and the trap answers those too. Two kinds cause trouble.</p><p>The first is symbol keys. Alongside ordinary string keys, JavaScript has a handful of special keys called symbols that the engine reaches for on its own, to ask an object how to handle a built-in operation. Logging an object makes it look up an inspection symbol, for...of looks up Symbol.iterator, dropping it into a template string looks up Symbol.toPrimitive. These are symbol keys, reached as node[Symbol.iterator], so a data key you happen to name iterator descends normally and is never involved. Our proxy treats every key alike, so it meets each of these symbol lookups with the descend branch and tries to build a child node. That node&#39;s key is path.join(&#39;.&#39;), and a symbol can&#39;t be joined into a string, so it throws Cannot convert a Symbol value to a string. Just logging a node would blow up.</p><p>The second is then. It&#39;s a plain string, so it doesn&#39;t crash, but it&#39;s the name promise-detecting code looks for. Plenty of libraries decide &quot;is this a <em>then</em>able?&quot; by checking whether value.then exists. Our proxy hands back a truthy child node for .then, so that check passes, the node gets mistaken for a promise, and something tries to unwrap it.</p><p>One guard at the top of the trap heads both off:</p><pre>get(_target, prop) {<br>  if (typeof prop === &#39;symbol&#39; || prop === &#39;then&#39;) return undefined<br>  // get, peek, set, or descend below<br>}</pre><p>Now a symbol read returns undefined, so the node behaves like an ordinary object that simply lacks those capabilities: console.log works again, and for...of fails with a clean &quot;not iterable&quot; instead of our internal crash. And .then is undefined, so nothing mistakes the node for a promise. A data path is always a plain string key, so handing back undefined for symbols and for then costs nothing real and stops the node from impersonating things it isn&#39;t.</p><p>The one collision left is a data key literally named get, set, or peek: the doors shadow it. Those three names are reserved, the same way they are in Legend.</p><h3>What stays unchanged</h3><p>Here’s the payoff for keeping the reader machinery separate from the store all this time. Every level is a node now, and a node is exactly what observe, computed, and use$ already knew how to talk to. So they all work at depth, unchanged.</p><pre>// an effect on a deep leaf<br>observe(() =&gt; console.log(&#39;doc is now&#39;, job$.attachments.doc.name.get()))<br><br>// a computed over a deep leaf<br>const docLabel = computed(() =&gt;<br>  job$.attachments.doc.name.get().toUpperCase(),<br>)<br><br>// a component reading a deep leaf<br>function DocName() {<br>  const name = use$(job$.attachments.doc.name)<br>  return &lt;span&gt;{name}&lt;/span&gt;<br>}</pre><p>use$(job$.attachments.doc.name) subscribes that component to one leaf, three levels down, and re-renders it when only that leaf changes. Batching still coalesces a burst of deep writes into a single wake-up. Cleanup still drops a deep dependency the moment a reader stops reading it. None of that code moved. We changed the shape the reader hangs on, not the reader itself.</p><h3>That’s it for today</h3><p>As always in this series, this is TMI in one article. Where it leaves us: It no longer peaks at one level. job$.attachments.doc.name is a first-class, trackable, settable node, and so is every path you can spell. The observable finally has the shape that real state has.</p><p>That’s the last piece of the core. One binding is still missing: observer, which tracks a whole component&#39;s render as a single reader instead of one use$ per value. That&#39;s Part 6. The magic, it turns out, was small the whole way down.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77c3525591e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maybe I’ll Understand Legend-State If I Build It, Part 4: Cool Toy. Now Make It Do Something]]></title>
            <link>https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-4-cool-toy-now-make-it-do-something-410fbcc4cbc0?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/410fbcc4cbc0</guid>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 12:27:44 GMT</pubDate>
            <atom:updated>2026-09-27T12:29:31.635Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Parts </em><a href="https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-1-it-starts-with-a-proxy-2d5123399217"><em>1</em></a><em>, </em><a href="https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-2-the-proxy-knows-now-it-has-to-care-a58b1a200c77"><em>2</em></a><em> and </em><a href="https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-3-ah-shit-now-it-cares-too-much-c86c4c97251c"><em>3</em></a><em> built a reactive core in plain JavaScript: </em><em>observable, </em><em>observe, </em><em>computed, synchronous batching, and dependency cleanup. It works, and it has never touched the screen. This part wires it to React with </em><em>use$, which turns out to be the same reader we already built, pointed at a re-render instead of a function call.</em></p><p>Quick recap of what we have. observable(x) gives you a value you read with .get() and write with .set(). observe(fn) runs fn and re-runs it whenever anything it read changes. computed derives a cached value the same way. A write notifies its readers synchronously, batched so a burst of writes wakes each reader once. All of it is plain JavaScript. None of it knows React exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK8ix9EJsbHquKT_I2TlPQ.webp" /></figure><h3>The components never update</h3><p>Drop an observable into a component and read it the obvious way:</p><pre>const job$ = observable({ status: &#39;queued&#39;, error_message: null })<br><br>function StatusBadge() {<br>  const status = job$.status.get()<br>  return &lt;span&gt;{status}&lt;/span&gt;<br>}</pre><p>It renders queued once and then never changes. Call job$.status.set(&#39;running&#39;) from anywhere and the badge sits there stale. React rendered the component, read the value, and moved on. It has no idea that job$.status is a thing that can change, or that this component should re-render when it does.</p><p>By the end of this part, one small change fixes it, swapping .get() for a hook we&#39;ll build called use$:</p><pre>function StatusBadge() {<br>  const status = use$(job$.status) // re-renders when status changes<br>  return &lt;span&gt;{status}&lt;/span&gt;<br>}</pre><p>That’s where we’re headed. To get there, the binding has two jobs. Read the current value, which we can already do with .get(). And subscribe the component so a change re-renders it. The second bit is what we are after, and it’s exactly what observe does, re-run something when what it read changes, except here &quot;re-run&quot; has to mean &quot;re-render this component.&quot;</p><h4>The useReducer way</h4><p>The obvious way to build the hook uses the tools you already know: useState (or useReducer) to force a re-render, useEffect to subscribe.</p><pre>function use$&lt;T&gt;(node: { get: () =&gt; T }): T {<br>  // dispatch, renamed forceRender: calling it bumps a counter we never read,<br>  // which is new state, so React re-renders<br>  const [, forceRender] = useReducer((n) =&gt; n + 1, 0)<br>  useEffect(() =&gt; {<br>    observe(() =&gt; {<br>      node.get()    // subscribe to this node<br>      forceRender() // and re-render when it changes<br>    })<br>  }, [])<br>  return node.get() // read the current value<br>}</pre><p>Now the StatusBadge from the top actually updates: a job$.status.set(&#39;running&#39;) from anywhere re-renders it. But there&#39;s a leak. When the component using the value unmounts, nothing stops its subscription. observe started listening and never gave us a way to turn it off, so the listener outlives the component, and every mount and unmount leaves another one behind.</p><p>So how do we fix it? we add an off switch to observe. It returns a disposer, a function that tears its subscription down:</p><pre>function observe(fn: () =&gt; void) {<br>  const subscription: Observer = Object.assign(<br>    () =&gt; track(subscription, fn),<br>    { deps: new Set&lt;Set&lt;Observer&gt;&gt;() },<br>  )<br>  subscription()<br>  return () =&gt; cleanup(subscription) // stop listening<br>}</pre><p>cleanup is the same helper from Part 3, it removes the subscription from every set it joined, so once the disposer runs, no future change reaches it. Now the observe returns it, and React can unsubscribe on unmount:</p><pre>useEffect(() =&gt; {<br>  return observe(() =&gt; {<br>    node.get()<br>    forceRender()<br>  })<br>}, [])</pre><p>The leak is closed. That fixes the obvious bug. But two deeper ones remain, and they’re the exact reasons React added a dedicated hook for this.</p><p>The first is a timing gap. useEffect runs after render and after paint. Between the moment the component reads node.get() during render and the moment the effect finally subscribes, the value can change, and nothing is listening yet. The component shows a stale value and never hears about the update. The window is small, but it&#39;s real, and it grows with however much work sits between render and commit.</p><p>The second is tearing. React’s concurrent rendering can pause a render partway through. If an observable changes during that pause, some components in the same render read the old value and some read the new one, so the screen shows two pieces of your state that never existed together. A plain useState subscription has no defense against this.</p><p>Both come down to the same thing: React needs to control exactly when the value is read and when the subscription happens, and a hand-rolled useState hook doesn&#39;t give it that control.</p><h4>use$ with useSyncExternalStore(React 18+)</h4><p>React ships a hook built for precisely this, connecting a component to a store that lives outside React: useSyncExternalStore. You give it two functions:</p><ul><li>subscribe(onStoreChange): start listening, call onStoreChange whenever the store changes, and return a function that stops listening.</li><li>getSnapshot(): return the current value.</li></ul><p>React handles the rest. It reads the snapshot at the right moments, subscribes at the right time (and re-checks the snapshot right after subscribing, which closes the timing gap), and guarantees a consistent read across a concurrent render, so no tearing. It’s the primitive every serious store library, Redux, Zustand, Jotai, and Legend-State, uses under the hood.</p><p>Our two functions fall right out of what we already have. getSnapshot is node.get(). subscribe is an observe that reads the node and pings React, returning the disposer we just added:</p><pre>import { useSyncExternalStore } from &#39;react&#39;<br><br>function use$&lt;T&gt;(node: { get: () =&gt; T }): T {<br>  return useSyncExternalStore(<br>    // subscribe: re-render whenever the node changes<br>    (onStoreChange) =&gt;<br>      observe(() =&gt; {<br>        node.get()      // read = subscribe to this node<br>        onStoreChange() // tell React it changed<br>      }),<br>    // getSnapshot: the current value<br>    () =&gt; node.get(),<br>  )<br>}</pre><p>That’s the whole binding. (This is React 18 and up; older React uses the use-sync-external-store shim, which is exactly what Legend imports.)</p><p>observe runs its function once immediately, so onStoreChange fires a single time the moment we subscribe. That&#39;s harmless: React responds by re-reading getSnapshot, sees the same value, and skips the render. It also means that if the value changed between render and subscribe, this immediate read catches it, the timing gap from the naive version, closed.</p><p>And notice we never wrote an equality check, yet use$ won&#39;t re-render for a no-op change. That&#39;s React&#39;s doing. getSnapshot returns the value itself, and useSyncExternalStore compares snapshots with Object.is. Our core over-notifies, a set fires even when the value is identical, but React compares the snapshot, sees no change, and declines to re-render. The React layer quietly absorbs the equality check our core skipped.</p><h3>It works, and it’s fine-grained</h3><p>With use$ reading through useSyncExternalStore, the badge updates on its own, and it does it fine-grained, the promise from the very first part. Each use$ subscribes the component to one node, so only the components that actually read a value re-render when it changes:</p><pre>function StatusBadge() {<br>  const status = use$(job$.status) // reads status<br>  return &lt;span&gt;{status}&lt;/span&gt;<br>}<br><br>function ErrorBanner() {<br>  const error = use$(job$.error_message) // reads error_message<br>  return error ? &lt;div&gt;{error}&lt;/div&gt; : null<br>}<br><br>job$.status.set(&#39;running&#39;)<br>// StatusBadge re-renders. ErrorBanner does not. It never read status.</pre><p>No selectors, no dependency arrays, no memo. StatusBadge re-renders because it read status and status changed; ErrorBanner stays put because it didn&#39;t.</p><p>Computed values work with no extra effort, because a computed is just a thing with a .get():</p><pre>const summary$ = computed(() =&gt;<br>  job$.error_message.get() ? &#39;failed&#39; : job$.status.get(),<br>)<br><br>function Summary() {<br>  return &lt;span&gt;{use$(summary$)}&lt;/span&gt;<br>}</pre><p>use$ doesn&#39;t care whether you hand it a plain observable node or a computed. Both read with .get(), both notify their subscribers, so both drive a component the same way.</p><h3>A component is just another reader</h3><p>The reactive work lives in our store, the reader machinery from Part 2, and the component just hangs off the end of it, re-rendering when the data it read changes. That makes it a reader, the same shape as observe. use$ is that machinery with one substitution: where observe&#39;s reaction is &quot;run the function again,&quot; use$&#39;s reaction is &quot;ask React to re-render.&quot; The subscribe-on-read, notify-on-write loop is identical; only the far end differs.</p><p>This is close to how Legend-State does it, with one difference worth flagging for later. Legend’s use$ also takes a selector, a function that computes a value, and a derived value can&#39;t be the snapshot: it gets a fresh identity on every call and would spin useSyncExternalStore in an infinite loop. Legend handles that with a version counter and its own equality check, in place of the free Object.is we lean on here. For a single node we need none of it, the value is a stable reference React can compare directly.</p><p>There’s one more binding we haven’t built yet: observer. Instead of one use$ per value, Legend lets you wrap a whole component so that every .get() in its render is tracked at once, one subscription for the entire component. It&#39;s the same tracking trick from Part 2, aimed at the render function instead of an observe callback: run the render as the current reader, collect everything it reads, and re-render when any of it changes. It&#39;s more ergonomic, you just call .get() anywhere, and more efficient, one subscription instead of N hooks. We stuck with the explicit use$ here because it keeps the mechanism visible; observer is the same idea scaled up to a whole component.</p><p>Yayy! So the core drives React now. It’s finally on the screen and it does it with the same reader we built three parts ago. But there’s a limitation running through every example above, our observables are one level deep. job$.status works. job$.attachments.doc.name does not. Real state nests, and so far ours flatly refuses to. It peaked at one level. Part 5 takes it all the way down. See ya there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=410fbcc4cbc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maybe I’ll Understand Legend-State If I Build It, Part 3: Ah Shit, Now It Cares Too Much]]></title>
            <link>https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-3-ah-shit-now-it-cares-too-much-c86c4c97251c?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c86c4c97251c</guid>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 09:47:47 GMT</pubDate>
            <atom:updated>2026-09-27T06:16:54.831Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hello there, beautiful people on the internet! Parts </em><a href="https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-1-it-starts-with-a-proxy-2d5123399217"><em>1</em></a><em> and </em><a href="https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-2-the-proxy-knows-now-it-has-to-care-a58b1a200c77"><em>2</em></a><em> built a working reactive core: observables, </em><em>observe, and </em><em>computed, with fine-grained tracking. It works, but it has two rough edges we flagged on the way at the end of part 2. Write to two fields in a row and every reader that reads both runs twice, once per write. And a reader that reads different things on different runs holds onto subscriptions it no longer uses. This part files both down. Still plain JavaScript, still no React.</em></p><p><em>Quick recap of where Part 2 left us. </em><em>observe runs a function and re-runs it whenever an observable it read changes. </em><em>computed derives a cached value the same way. Both work by pushing themselves onto a shared </em><em>observerStack before they run, so every </em><em>.get() can see who is reading and add them to that key&#39;s subscriber set. A </em><em>.set() then notifies everyone in the set. That is the whole loop. Now we make it hold up under real use.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK8ix9EJsbHquKT_I2TlPQ.webp" /></figure><h3>The write that runs twice</h3><p>Let’s jump straight into what the title of this part is talking about. Take a reader that reads two fields:</p><pre>const job$ = observable({ status: &#39;queued&#39;, error_message: null })<br><br>observe(() =&gt; {<br>  console.log(job$.status.get(), job$.error_message.get())<br>})</pre><p>Now update both, one after the other:</p><pre>job$.status.set(&#39;running&#39;)<br>job$.error_message.set(&#39;timeout&#39;)</pre><p>The reader runs twice. The first set notifies it, because it read status, and it re-runs. The second set notifies it again, because it read error_message, and it re-runs again. But logically this was one update: a job went from queued to failed. We rendered an in-between state that never mattered, and we did the work twice.</p><p>The cause is that set notifies immediately, the moment a value changes. Two changes, two notifications, two re-runs. What we want is to let a burst of writes settle, then notify each affected subscriber once.</p><h4>Batching: run each reader once</h4><p>The easier fix is to give the caller a way to say “these writes belong together.” Let a burst of writes settle, then run each affected reader once. That is what we’re building: a batch function you wrap your writes in.</p><pre>batch(() =&gt; {<br>  job$.status.set(&#39;running&#39;)<br>  job$.error_message.set(&#39;timeout&#39;)<br>})<br>// reader runs once, after both writes have landed</pre><p>Pretty simple, it’s two pieces: a counter and a queue. beginBatch opens a group and endBatch closes it. While a batch is open, notifications wait in the queue; when the last one closes, we run them all.</p><pre>let batchDepth = 0 // how many batches are open; 0 means none<br>const pendingEffects = new Set&lt;Observer&gt;() // effects waiting for the flush<br><br>function beginBatch() {<br>  batchDepth++<br>}<br><br>function endBatch() {<br>  if (--batchDepth === 0) flush()<br>}<br><br>function flush() {<br>  const toRun = [...pendingEffects]<br>  pendingEffects.clear()<br>  for (const effect of toRun) effect()<br>}<br><br>function batch(fn: () =&gt; void) {<br>  beginBatch()<br>  try {<br>    fn()<br>  } finally {<br>    endBatch()<br>  }<br>}</pre><p>And batchDepth is a counter, not a boolean, because there can be nested batch calls. An inner batch increments and decrements without flushing, and only the outermost batch, the one that brings the depth back to zero, actually flushes. Same shape as the observer stack. Nesting is handled by counting in and out and it doesn’t the outcome; all the writes collapse into one flush.</p><p>When a value changes, we notify its subscribers, and during a batch that notification is exactly what we want to defer. But we can’t defer everything. A computed’s invalidation is a subscriber too, and if we deferred it like any other, a computed read in the middle of a batch would be stale:</p><pre>const sum$ = computed(() =&gt; a$.v.get() + b$.v.get())<br>sum$.get() // 3<br><br>batch(() =&gt; {<br>  a$.v.set(10)<br>  sum$.get() // if invalidation were deferred, this would still say 3<br>})</pre><p>a is now 10, but sum$, which is a + b, would still report the old 3. A value and the thing derived from it disagree, mid-batch. That inconsistency has a name, a glitch. The fix is to treat the two kinds of subscriber differently: a computed is marked dirty <em>immediately</em>, so any read of it recomputes fresh, and only effects are deferred to the flush. That decision lives in a notify helper:</p><pre>function notify(subs: Set&lt;Observer&gt;) {<br>  for (const sub of [...subs]) {<br>    if (sub.isComputed) sub() // computed: mark dirty now, so reads stay fresh<br>    else pendingEffects.add(sub) // effect: defer to the flush<br>  }<br>}</pre><p>For that to work, a subscriber has to say which kind it is. An observe subscription is an effect and stays untagged; a computed&#39;s invalidate gets tagged isComputed, so we update the type as:</p><pre>type Observer = {<br>  (): void<br>  isComputed?: boolean<br>}</pre><p>And we attach the isComputed to the invalidate observer.</p><pre>// computed&#39;s invalidate, now tagged and routing through notify<br>const invalidate: Observer = Object.assign(<br>  () =&gt; {<br>    if (dirty) return<br>    dirty = true<br>    notify(subscribers) // computeds sync, effects deferred, all the way down<br>  },<br>  { isComputed: true },<br>)</pre><p>Now set can take part. It wraps itself in a batch and routes its subscribers through notify:</p><pre>set(value) {<br>  beginBatch()<br>  try {<br>    store[key] = value<br>    const subs = subscribers.get(key)<br>    if (subs) notify(subs)<br>  } finally {<br>    endBatch()<br>  }<br>}</pre><p>With set and notify in place, the batch() we opened the section with, finally works. Wrap the two writes, and inside the callback each set bumps the depth to 2 and back to 1, so neither one flushes; then the outer batch closes, the depth hits 0, and the reader runs once.</p><p>Automatic batching comes for free on top of that. A lone set, with no batch() around it, is simply a batch of one: it opens, applies, closes, hits zero, and flushes right away, exactly like Part 2. But writes that pile up inside an already-open batch defer to the outermost flush. That nesting is the whole trick, and it keeps everything synchronous: the flush happens the instant the outermost batch closes, before your next line runs.</p><p>And the glitch(computed fields having a stale value) never happens. Because invalidate runs synchronously, sum$ flips to dirty the instant a changes, so the sum$.get() inside the batch above recomputes to 30, never the stale 3. This is how Legend-State does it: synchronous batching where only the notifications to effects are deferred, never the computation. A .get() on a computed always returns the current value, batch or not.</p><h3>The subscription that overstays</h3><p>Now coming to the second rough edge is quieter, and it only shows up once a reader reads <em>different</em> things on different runs.</p><p>The problem is, a reader subscribes to whatever it reads on each run. What it never does is <em>un</em>-subscribe from what it read on previous runs. With unconditional reads that is invisible, because every run reads the same keys. Add a branch and it leaks:</p><pre>const ui$ = observable({ showError: false, status: &#39;queued&#39;, error: &#39;none&#39; })<br><br>// Reads showError, then EITHER status OR error depending on the flag,<br>// so its dependency set changes from one run to the next.<br>observe(() =&gt; {<br>  if (ui$.showError.get()) {<br>    console.log(&#39;error:&#39;, ui$.error.get())<br>  } else {<br>    console.log(&#39;status:&#39;, ui$.status.get())<br>  }<br>})<br>// First run: showError is false, so it takes the else branch.<br>// Reads showError and status, and subscribes to both.<br>// logs &quot;status: queued&quot;<br><br>ui$.showError.set(true)<br>// showError changed, so the reader re-runs, now taking the if branch.<br>// It reads showError and error, and subscribes to both.<br>// It did NOT read status this time, but it is still in status&#39;s<br>// subscriber set from the first run. Nothing ever removed it.<br>// logs &quot;error: none&quot;<br><br>ui$.status.set(&#39;running&#39;)<br>// status changed, but the reader no longer uses status at all.<br>// Ideally nothing happens. Instead the stale subscription re-runs it,<br>// wasted work for a value it now ignores.<br>// logs &quot;error: none&quot;   (ran again, same output)</pre><p>That last set is the bug. The reader stopped depending on status the moment it took the if branch, but the subscription to status is still there, so changing status re-runs a reader that ignores it. The subscription overstayed its welcome.</p><p>The reason is that the link between a reader and its keys is one-way. A key’s subscriber set knows its readers, but a reader has no idea which sets it is in. So it can add itself to new sets on each run, but it can never remove itself from old ones.</p><p>The fix is to make the link two-way, and to clean up before every re-run. Each reader remembers the sets it joined. Before it runs again, it removes itself from all of them, then rebuilds the list from scratch by reading again. Whatever it reads this time is what it stays subscribed to. Whatever it skips this time, it drops.</p><p>First, the reader has to carry its dependencies. We extend the Observer from the batching section with one more field, the set of subscriber sets it currently belongs to:</p><pre>type Observer = {<br>  (): void<br>  isComputed?: boolean // from the batching section<br>  deps: Set&lt;Set&lt;Observer&gt;&gt; // the subscriber sets this reader is currently in<br>}</pre><p>Then get records the back-link. When a key&#39;s set adds the reader, the reader notes that set in return:</p><pre>get() {<br>  const observer = currentObserver()<br>  if (observer) {<br>    let subs = subscribers.get(key)<br>    if (!subs) subscribers.set(key, (subs = new Set()))<br>    subs.add(observer) // the set knows the reader<br>    observer.deps.add(subs) // and now the reader knows the set<br>  }<br>  return store[key]<br>}</pre><p>A small helper tears down every current subscription:</p><pre>function cleanup(observer: Observer) {<br>  for (const subs of observer.deps) subs.delete(observer)<br>  observer.deps.clear()<br>}</pre><p>And observe calls it first on every run, before it reads anything:</p><pre>function observe(fn: () =&gt; void) {<br>  const subscription: Observer = Object.assign(<br>    () =&gt; {<br>      cleanup(subscription) // drop every old subscription first<br>      observerStack.push(subscription)<br>      try {<br>        fn() // then rebuild only what is actually read this time<br>      } finally {<br>        observerStack.pop()<br>      }<br>    },<br>    { deps: new Set&lt;Set&lt;Observer&gt;&gt;() },<br>  )<br>  subscription()<br>}</pre><p>Now walk the branch case again:</p><ol><li><strong>First run</strong> (error_message is null): reads status. So status&#39;s set holds the subscription, and the subscription&#39;s deps holds status&#39;s set.</li><li><strong>error_message is set:</strong> the subscription re-runs. cleanup removes it from status&#39;s set, which is now empty, and clears its deps. Then fn runs, takes the if branch, and reads error_message. Now error_message&#39;s set holds the subscription, and deps holds error_message&#39;s set. The subscription is no longer in status&#39;s set.</li><li><strong>status changes:</strong> its set is empty, so nothing re-runs. Before the fix, the reader would have run for a value it stopped caring about. Fixed.</li></ol><p>computed needs the same treatment, for the same reason. Its invalidate is a reader too, so it gets a deps set, and its recompute inside get calls cleanup before re-reading, exactly as observe does:</p><pre>const invalidate: Observer = Object.assign(<br>  () =&gt; {<br>    if (dirty) return<br>    dirty = true<br>    notify(subscribers)<br>  },<br>  { isComputed: true, deps: new Set&lt;Set&lt;Observer&gt;&gt;() }, // deps added<br>)<br><br>// ...and the recompute inside get() now cleans up first:<br>if (dirty) {<br>  cleanup(invalidate) // drop old dependencies<br>  observerStack.push(invalidate)<br>  try {<br>    cached = fn() // rebuild only what it reads now<br>  } finally {<br>    observerStack.pop()<br>  }<br>  dirty = false<br>}</pre><p>For a computed, the missing cleanup is worse than a wasted wake-up. A dependency it stopped reading but stayed subscribed to keeps marking it dirty every time that value changes, so it recomputes on the next read for an input it no longer uses. Cleanup is what keeps a computed recomputing only for what it actually reads now.</p><p>Few things worth holding onto before moving on.</p><p>First, subscriptions are provisional. Each one lasts exactly one run, and the next run has to re-earn it by actually reading the value. cleanup wipes them all, and the reads rebuild them, so what stays subscribed is always exactly what the code read this time.</p><p>Second, the copy-before-iterate trick from Part 2 still matters, the snapshot we loop over instead of the live set:</p><pre>for (const sub of [...subs]) // a copy, so mutating subs mid-loop is safe</pre><p>A re-run changes subscriber sets while we walk them (cleanup removing entries, the reads re-adding them), so iterating a copy rather than the live set keeps it safe.</p><p>Third, it isn’t free. Each reader now carries its dependency sets and tears them down and rebuilds them every run. In practice that cost is nothing, and Vue, Preact Signals, and Solid all pay it.</p><p>This is our core that we’ve made robust now. It reacts to exactly what changed, collapses a burst of writes into a single flush, and forgets what it stops reading. But it has never once touched the screen. Everything so far is plain JavaScript logging to a console.</p><p>Alsthough so for what we’ve built looks like just a cool toy .Part 4 changes that. We wire the whole thing to React with use$, and it turns out to be nothing new, it&#39;s the same reader we&#39;ve been building, with one twist. Where observe re-runs a function, use$ re-renders a component. A component becomes just another thing that reads observables and reacts when they change. That&#39;s also why the core has stayed pure JavaScript this whole time. React is just an adapter we&#39;re bolting on, and the same core could drive Vue, Solid, or anything else with a binding of its own. But one thing at a time. See ya in part 4</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c86c4c97251c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maybe I’ll Understand Legend-State If I Build It, Part 2: The Proxy Knows. Now It Has to Care]]></title>
            <link>https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-2-the-proxy-knows-now-it-has-to-care-a58b1a200c77?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a58b1a200c77</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 20:14:49 GMT</pubDate>
            <atom:updated>2026-09-20T20:14:49.060Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hello there, beautiful people on the internet! In </em><a href="https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-1-it-starts-with-a-proxy-2d5123399217"><em>Part 1</em></a><em> we built </em><em>observable(), a </em><em>Proxy that routes every read and write through a per-key node with a typed </em><em>.get()/</em><em>.set() API. It intercepts perfectly and does nothing with it: the &quot;remember the reader&quot; and &quot;notify subscribers&quot; spots are still </em><em>console.logs. This part makes them real. By the end we&#39;ll have fine-grained reactivity working in plain JavaScript, no React yet.</em></p><p><em>Quick recap of where Part 1 left the code, so this part stands on its own. </em><em>observable(x) boxes primitives under a </em><em>value key, keeps objects as-is, and hands back a </em><em>Proxy whose every property access returns a node, a </em><em>{ get, set } pair scoped to one key. Reads and writes only ever go through those nodes; there&#39;s no raw assignment path. That single doorway per key is the thing we&#39;re about to hang a subscription list on.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK8ix9EJsbHquKT_I2TlPQ.webp" /></figure><p>Before we start, let’s clear out on what we’re building in this part. Two reactive functions. observe takes a function, runs it once, and then re-runs it automatically whenever any observable it read changes. That&#39;s how you make something happen in response to state: log a value, save it, redraw a view. computed is its close cousin. It derives a value from other observables and caches it, recomputing only when one of its inputs changes. The thing to hold onto is that both are <em>readers</em>: they read observables and re-run when what they read changes. Legend’s word for a reader is an <em>observing context</em>, and in the code each one is an Observer. So the first problem to solve is letting an observable figure out who is reading it.</p><h3>Who’s reading?</h3><p>Now, back to the console.logs we’ve put in part 1. The get line needs to remember the reader, and the set line needs to notify the subscribers.</p><p>Starting with what we have to store. For set to notify a key&#39;s readers when it changes, each key has to keep track of who its readers are. So we expand the observable to maintain a set of subscribers per key. A reader is just a function we can re-run. Today that’s observe or computed; in Part 4 it will be a React component too, wired so that a change re-renders it instead of re-running a plain function. Same kind of reader either way. So the record is a map from key to a set of them:</p><pre>type Observer = () =&gt; void<br><br>// This goes in the observable func<br>const subscribers = new Map&lt;string, Set&lt;Observer&gt;&gt;()</pre><p>But we don’t want the code using the observable to build these lists by hand, or to register itself manually. Subscribing has to happen on its own, as a side effect of reading. And on the other end, set has to look up the subscribers for the key that changed and tell every one of them to react.</p><p>You know what, we can do so when a value is being read. A reader should join a key’s list at the exact moment it reads that key. But here’s the snag: when job$.status.get() runs, the node knows its key is status, and it knows it&#39;s being read, but it has no idea <em>who</em> is reading. The reader is some reader running further up the call stack, and the node holds no reference to it.</p><p>So we give the node a way to find out. We keep one module-level variable that holds whichever reader is running right now:</p><pre>let currentObserver: Observer | null = null</pre><p>Before a reader (an observe or a computed) runs, it stores itself in currentObserver. Then any get that fires during the run can read that variable, find the reader, and drop it into the list for the key being read. That&#39;s how a reader lands on a subscriber list: not by registering itself explicitly, but by being the current reader at the moment of a get.</p><p>Let’s take some time and discuss why this sits at module scope, out in the open, instead of being passed around. The two halves that need it never actually meet. observe is the code that knows who is running. get, tucked inside observable, is the code that needs to know. But an observable holds no reference to the readers reading it, and a reader holds no reference to the observables it will touch. They&#39;re written independently and wired together only at runtime, by the reads themselves. So get can&#39;t just be handed the reader as an argument. It needs a shared place to look, one that both sides can reach without knowing anything about each other. A single module-level variable is that shared place. It also means every observable consults the same spot, which is exactly what lets one reader subscribe across several different observables at once, something we&#39;ll lean on later.</p><p>Here’s all of it together. The subscriber map lives inside each observable, get records the current reader into the right key&#39;s set, and set function walks that subscribers set to notify:</p><pre>function observable&lt;T&gt;(initialValue: T): Observable&lt;T&gt; {<br>  const isObject = initialValue !== null &amp;&amp; typeof initialValue === &#39;object&#39;<br>  const store: Record&lt;string, unknown&gt; = isObject<br>    ? { ...(initialValue as object) }<br>    : { value: initialValue }<br><br>  // one subscriber set per key<br>  const subscribers = new Map&lt;string, Set&lt;Observer&gt;&gt;()<br><br>  const node = (key: string): Node&lt;unknown&gt; =&gt; ({<br>    get() {<br>      // remember the reader<br>      if (currentObserver) {<br>        let subs = subscribers.get(key)<br>        if (!subs) subscribers.set(key, (subs = new Set()))<br>        subs.add(currentObserver)<br>      }<br>      return store[key]<br>    },<br>    set(value) {<br>      store[key] = value<br>      // notify subscribers<br>      const subs = subscribers.get(key)<br>      if (subs) for (const subscription of [...subs]) subscription()<br>    },<br>  })<br><br>  const proxy = new Proxy(store, {<br>    get(_store, key: string) {<br>      if (!isObject) return node(&#39;value&#39;)[key as keyof Node&lt;unknown&gt;]<br>      return node(key)<br>    },<br>  })<br><br>  return proxy as Observable&lt;T&gt;<br>}</pre><p>Both placeholders are functional now. get checks whether anyone is reading, and if so adds them to this key&#39;s set. set writes the value, then re-runs everyone in that set.</p><p>That last line in set :</p><pre>if (subs) for (const subscription of [...subs]) subscription()</pre><p>The if (subs) check bails when nobody has ever read this key. No set means no readers, so there is nothing to notify. The [...subs] part copies the set into a fresh array before we loop over it, and that copy matters. Calling subscription() re-runs a reader, which re-reads its observables, which calls subs.add(...) on this same set. Looping over a Set while you add to it is asking for trouble: you can skip a member, hit one twice, or loop forever. Copying first means we notify the members as they were at write time, and any new subscriptions land safely for next time. Each subscription in the set is a reader, the function we are about to write in observe. So notifying really does just mean calling every function that read this key.</p><p>There’s still something missing here. Everything is wired up, but nothing has actually subscribed yet. get is ready to record a reader and set is ready to notify one, but currentObserver is still null and nothing ever changes that. So the if (currentObserver) check in get never passes, and every subscriber list stays empty. The last missing piece is the thing that sets currentObserver in the first place. That&#39;s observe:</p><pre>function observe(fn: Observer) {<br>  const subscription = () =&gt; {<br>    currentObserver = subscription<br>    try {<br>      fn()<br>    } finally {<br>      currentObserver = null<br>    }<br>  }<br>  subscription()<br>}</pre><p>observe takes a function, fn, and runs it once right away. That fn is the thing doing the subscribing: the observables it reads are the ones it will re-run for. It doesn&#39;t land in the subscriber lists directly, though. observe wraps fn in subscription and points currentObserver at that wrapper before running fn. So every get inside fn registers subscription, the re-runnable stand-in for your function. When one of those values changes later, set calls subscription, which re-runs fn, re-points currentObserver, and re-reads, picking up whatever it reads this time. The finally clears the pointer afterward, so reads outside any reader don&#39;t accidentally subscribe to nothing. We&#39;re using finally because the function could error out leaving the currentObserver uncleared.</p><p>Here’s something working after all that hard work:</p><pre>const job$ = observable({ status: &#39;queued&#39;, error_message: null })<br><br>observe(() =&gt; {<br>  console.log(&#39;status is now:&#39;, job$.status.get())<br>})<br>// logs immediately: &quot;status is now: queued&quot;<br><br>job$.status.set(&#39;running&#39;)<br>// reader re-runs → logs: &quot;status is now: running&quot;<br><br>job$.error_message.set(&#39;timeout&#39;)<br>// nothing happens: the reader never read error_message</pre><p>That last line is the point of the whole thing. The reader(<em>observe function</em>) read status and nothing else, so it lives in the status set and no other. Changing error_message notifies an empty set, so nothing happens. This is fine-grained reactivity, and there is no diffing and no dependency array behind it. It is just this: whoever read the key is in that key&#39;s set.</p><h4>Deriving values: computed()</h4><p>observe runs a function for its side effects. computed is the other thing you&#39;ll want from the same machinery: a value derived from other observables, one that keeps itself up to date.</p><p>Say you want a one-line summary of a job. It depends on two fields, and you’d like to read it like any other value:</p><pre>const job$ = observable({ status: &#39;queued&#39;, error_message: null })<br><br>const summary$ = computed(() =&gt;<br>  job$.error_message.get()<br>    ? `failed: ${job$.error_message.get()}`<br>    : job$.status.get(),<br>)<br><br>summary$.get() // &quot;queued&quot;<br>job$.status.set(&#39;running&#39;)<br>summary$.get() // &quot;running&quot;<br>job$.error_message.set(&#39;timeout&#39;)<br>summary$.get() // &quot;failed: timeout&quot;</pre><p>The tempting way to build this is to lean on what we&#39;ve already built, observe. A reader already re-runs when its dependencies change, so point one at the derivation and stash the result in an observable:</p><pre>function computed&lt;T&gt;(fn: () =&gt; T): { get: () =&gt; T } {<br>  const holder = observable&lt;T&gt;(undefined as T)<br>  observe(() =&gt; holder.set(fn()))<br>  return { get: () =&gt; holder.get() }<br>}</pre><p>And it works. holder caches the value, the reader recomputes it whenever status or error_message changes, and reading summary$.get() inside another reader subscribes to it the usual way.</p><p>But it recomputes too eagerly. The reader runs on every dependency change, whether or not anyone is reading the computed. If the derivation is expensive and nothing is displaying it right now, we still pay for it on every set. A real computed is lazy. It recomputes only when someone reads it, and only if a dependency actually changed since the last read.</p><p>Here’s the lazy version. While it recomputes, it points currentObserver at its own reader, the same move observe makes, so the values it reads get tracked:</p><pre>function computed&lt;T&gt;(fn: () =&gt; T): { get: () =&gt; T } {<br>  let cached: T<br>  let dirty = true<br>  const subscribers = new Set&lt;Observer&gt;()<br><br>  // Runs when a dependency changes: go stale, wake our own readers.<br>  const invalidate: Observer = () =&gt; {<br>    if (dirty) return<br>    dirty = true<br>    for (const subscription of [...subscribers]) subscription()<br>  }<br><br>  return {<br>    get() {<br>      // Whoever is reading us now depends on us.<br>      if (currentObserver) subscribers.add(currentObserver)<br><br>      // Recompute only if something changed since the last read.<br>      if (dirty) {<br>        currentObserver = invalidate<br>        try {<br>          cached = fn()<br>        } finally {<br>          currentObserver = null<br>        }<br>        dirty = false<br>      }<br><br>      return cached<br>    },<br>  }<br>}</pre><p>A computed is two things at once. To the observables it reads, it’s a reader: we point currentObserver at invalidate before running fn, so each dependency drops invalidate into its subscriber set. To whoever reads the computed, it&#39;s an observable, and like any observable it keeps its own list of subscribers, the subscribers set at the top. A plain observable keeps one such set per key; a computed is a single value, so it needs just one. Reading the computed from inside a reader adds that reader to this set, and when the computed goes stale, invalidate wakes everyone in it.</p><p>That dual role is the whole idea. When a dependency changes, the computed doesn’t recompute. It calls invalidate, which flips dirty and wakes its own subscribers. If one of them is a reader, that reader re-runs, reads summary$.get(), finds it dirty, and triggers the recompute right then. If nothing is reading the computed, it just sits there marked dirty until someone does. Work happens on read, not on write.</p><p>Now, about if (dirty) returnguard in invalidate, being stale is a one-way state: once the computed is marked dirty it stays dirty until the next read recomputes it. Consider this example to understannd the flow:</p><pre>const a$ = observable({ v: 1 })<br>const b$ = observable({ v: 2 })<br><br>const sum$ = computed(() =&gt; a$.v.get() + b$.v.get())<br><br>sum$.get() // returns 3, computes and caches it; dirty is now false<br><br>a$.v.set(10) // invalidate runs: dirty was false, flip to true (no recompute)<br>b$.v.set(20) // invalidate runs: dirty already true, guard returns at once<br><br>sum$.get() // returns 30, recomputes once here; dirty back to false<br><br>a$.v.set(99) // invalidate runs: dirty false again, flip to true</pre><p>One more detail, there’s no equality check, so a recompute that lands on the same value still notifies. A real library skips that. Ours doesn’t, so a subscriber may occasionally re-run for a value that didn’t actually change, which is harmless for the simple computeds we’re building.</p><h4>Huston we have another problem</h4><p>Now the question is, what happens when computed value is read inside an observe?</p><pre>const job$ = observable({ status: &#39;queued&#39;, error_message: null })<br>const summary$ = computed(() =&gt; job$.status.get())<br><br>observe(() =&gt; {<br>  console.log(&#39;summary:&#39;, summary$.get())          // reads the computed<br>  console.log(&#39;errors:&#39;, job$.error_message.get())  // read AFTER the computed<br>})</pre><p>You would expect this observe to re-run whenever status or error_message changes. It won&#39;t. Change error_message and nothing happens.</p><p>And why is that? The observe sets currentObserver to its own subscription and starts. It reads summary$, which adds the observe to the computed&#39;s subscribers, fine so far. Then the computed recomputes, sets currentObserver to its invalidate, reads status, and in its finally sets currentObserver back to null. Control returns to the observe, but currentObserver is null now. So when the observe reads error_message next, there is no current reader, and nothing subscribes. The observe quietly stopped tracking halfway through its own run.</p><p>The trouble is that currentObserver is a single variable, and it can only hold one reader at a time. But reading a computed inside an observe means two readers are live at once: the observe on the outside, the computed&#39;s invalidate on the inside. The inner one finishes first and clears the variable, and the outer one never gets it back.</p><p>What we need is for each reader to restore the previous one when it finishes, instead of blowing it away. What data structure solves this? Ding ding ding! That is a stack: push on the way in, pop on the way out, so when the inner reader finishes, the outer one is still sitting underneath.</p><pre>const observerStack: Observer[] = []<br><br>function currentObserver() {<br>  return observerStack[observerStack.length - 1] ?? null<br>}</pre><p>We replace the currentObserver assignments with push and pop on the observer stack, observe changes to:</p><pre>function observe(fn: Observer) {<br>  const subscription = () =&gt; {<br>    observerStack.push(subscription)<br>    try {<br>      fn()<br>    } finally {<br>      observerStack.pop()<br>    }<br>  }<br>  subscription()<br>}</pre><p>computed changes the same way. Its get calls currentObserver() to find its reader, and pushes invalidate onto the stack while it recomputes:</p><pre>get() {<br>  const observer = currentObserver()<br>  if (observer) subscribers.add(observer)<br><br>  if (dirty) {<br>    observerStack.push(invalidate)<br>    try {<br>      cached = fn()<br>    } finally {<br>      observerStack.pop()<br>    }<br>    dirty = false<br>  }<br><br>  return cached<br>}</pre><p>And the node’s get reads the top of the stack too, instead of the bare variable:</p><pre>get() {<br>  const observer = currentObserver()<br>  if (observer) {<br>    let subs = subscribers.get(key)<br>    if (!subs) subscribers.set(key, (subs = new Set()))<br>    subs.add(observer)<br>  }<br>  return store[key]<br>}</pre><p>Now with this fix in place, trace the same example. The observe pushes its subscription, so the stack is [subscription]. Reading summary$ pushes invalidate on top, giving [subscription, invalidate], status subscribes invalidate, then the computed pops back to [subscription]. The observe reads error_message with subscription still on top, so error_message subscribes it. Both dependencies tracked. Change either one and the observe re-runs.</p><p>This is why the “who is reading” pointer has to be a stack. The moment one reader can run inside another, and reading a computed makes that happen constantly, a single variable loses the outer one.</p><p>That’s it for today, that’s the core reactive loop. A read registers a dependency, a write notifies the subscribers, and observe and computed are the things doing the reading. Almost everything else a signals library gives you is built on top of these few moves.</p><p>There are two more problems to fix: stale subscriptions never get cleaned up, and there’s no batching for writes. We’ll understand and fix both of them in Part 3, see ya there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a58b1a200c77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maybe I’ll Understand Legend-State If I Build It — Part 1: It Starts With a Proxy]]></title>
            <link>https://medium.com/@so_deep.dev/maybe-ill-understand-legend-state-if-i-build-it-part-1-it-starts-with-a-proxy-2d5123399217?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d5123399217</guid>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[proxy]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 06:38:57 GMT</pubDate>
            <atom:updated>2026-09-20T12:11:54.555Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hello there, beautiful people on the internet! This is the first part of a series where we rebuild the bare essentials of a signal-based state library, the kind of thing Legend-State does, from scratch. Part 1 is all about the</em> Proxy <em>underneath it: by the end, we&#39;ll have a working</em> observable() <em>that intercepts reads and writes behind a clean, typed</em> .get()/.set() <em>API. It won&#39;t be reactive yet (that&#39;s Part 2), but it&#39;s the foundation everything else sits on. Later parts add reactivity (</em><em>observe, </em><em>computed), batching, the React binding (</em><em>use$), and finally recursive nesting, so the wrapper goes as deep as your data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK8ix9EJsbHquKT_I2TlPQ.png" /></figure><p>I reach for Legend-State in real code all the time. observable(), use$, computeds. I know how to <em>use</em> them. I just don&#39;t really know what they <em>do</em>. And every time jobs$[id].status.get() re-renders the one component reading that status and nothing else, some part of me files it under <em>magic</em> and moves on.</p><p>This series is me refusing to move on. Not by reading the source top to bottom(I tried), but by rebuilding the bare essentials from an empty file, using only the pieces I actually care about, until there’s nothing left to hand-wave.</p><p>Because that’s all <em>magic</em> ever is, the parts you haven’t looked inside yet. Legend-State’s fine-grained reactivity feels uncanny the first time you see it. So instead of trying to understand the whole thing at once, I’m going to build a much dumber version and see if I can work my way into understanding it.</p><p>So let’s build it. Not the whole library, just the bare essentials. And we start with a Proxy that knows the instant you touch it.</p><h3>The proxy trap: get/set interception</h3><p>Start with the simplest possible thing: a function that takes a plain object and wraps it in a Proxy.</p><pre>function observable&lt;T extends object&gt;(initialValue: T) {<br>  const value = { ...initialValue }<br>  const proxy = new Proxy(value, {<br>    get(target, key: string) {<br>      console.log(`read: ${key}`)<br>      return target[key as keyof T]<br>    },<br>    set(target, key: string, newValue) {<br>      console.log(`write: ${key}`)<br>      target[key as keyof T] = newValue<br>      return true<br>    },<br>  })<br>  return proxy<br>}</pre><p>That’s it. That’s the whole trick, at least the shape of it.</p><p>get and set are traps. Every time you touch a property on the proxy, JavaScript routes the read or write through your function instead of hitting the object directly.</p><pre>const job$ = observable({ status: &#39;queued&#39;, error_message: null })<br>job$.status // logs: &quot;read: status&quot;<br>job$.status = &#39;running&#39; // logs: &quot;write: status&quot;</pre><p>Right now, all we’re doing is logging. Not useful yet. But notice what we <em>can</em> do here that a plain object can’t: intercept every read and write, per key, with zero extra syntax on the consumer’s side.</p><p>job$.status looks exactly like reading a normal property. That&#39;s the part that makes this feel like magic later: there&#39;s no .subscribe() call, no selector function, just a property access that happens to also be a wiretap.</p><p>The next piece is turning “read” into “someone depends on this” and “write” into “go tell them.”</p><blockquote>Real Legend-State doesn’t return raw values from get, it returns nested observables, so jobs$[id].status is itself wrapped, all the way down. We&#39;re keeping it flat for now: one level, single-key objects, which is all we need to prove the mechanism. The recursive wrapper is a real piece of work, and it&#39;s where this series ends up: Part 5 is entirely about going deep(If I don’t give up before I get there lol).</blockquote><h4>Looking closer at the traps</h4><p>Think about what normally happens when you write job.status. JavaScript looks up the status key on the object and hands you the value. Done. There&#39;s no hook, no interception point. The language just does the lookup and moves on.</p><p>Same with job.status = &#39;running&#39;: it finds the slot and overwrites it. You never get a chance to run code in between.</p><p>A Proxy changes that. It sits <em>in front of</em> the real object (the &quot;target&quot;) and lets you define trap functions that fire on those fundamental operations. When you read a property, the get trap runs first and decides what to return. When you write one, the set trap runs first and decides what to do with the new value.</p><p>The get trap receives two arguments that matter to us: the target (the real underlying object) and the key (the property name being read, as a string). Our job inside get is eventually to return target[key] (the actual value), but we get a moment <em>before</em> that return to do bookkeeping.</p><p>That “moment before” is the entire hook we’re going to hang reactivity on.</p><p>The set trap receives the target, the key, and the incoming newValue. We write it into the target with target[key] = newValue, and (this part trips people up) we <strong>must return</strong> true to tell JavaScript the write succeeded. Forget it and we&#39;ll get a TypeError in strict mode.</p><p>And just like get, we now have a moment <em>after</em> the write to do bookkeeping, notify anyone who cared about this key.</p><p>So the shape of the whole system is already visible here, even though we haven’t written the reactive part yet:</p><ul><li>get → &quot;someone is <strong>reading</strong> this key, remember them&quot;</li><li>set → &quot;this key <strong>changed</strong>, go tell whoever we remembered&quot;</li></ul><p>The reactive model we’re building is <em>just</em> those two steps: on read, remember who’s asking; on write, tell them.</p><p>Notice the asymmetry, too. The get trap does its bookkeeping <em>before</em> returning the value (you have to register the reader while you still know who&#39;s reading). The set trap does its bookkeeping <em>after</em> the write lands (no point notifying subscribers about a value that isn&#39;t in the target yet).</p><p>Small detail, but it’s why the code has the “moment before” on reads and the “moment after” on writes.</p><p>Right now, both of those steps are still just console.logs. Section 2 is where &quot;remember the reader&quot; and &quot;notify subscribers&quot; get real implementations.</p><h3>A quick problem: what about primitives?</h3><p>There’s one annoying problem with our implementation so far: Proxy only works with objects.</p><p>Try this:</p><pre>new Proxy(0, {})</pre><p>JavaScript isn’t having it. You get a TypeError.</p><p>That’s a problem because a state library obviously needs to be able to make an observable out of something like a number, string, or boolean too.</p><p>The usual trick is to box the primitive inside an object:</p><pre>{ value: 0 }</pre><p>Now we have something that can be wrapped in a Proxy.</p><p>The important part isn’t really the box itself. It’s that we now have a consistent way to represent both an observable object and an observable primitive. Everything can eventually expose the same .get() / .set() interface, regardless of what&#39;s underneath.</p><h4>Locking in the door: .get() / .set()</h4><p>Let’s build the version that delivers on that promise: box primitives when we need to, and put .get() / .set() on everything.</p><p>The key move is small. Reading a property off the proxy no longer returns the raw value. It returns a little { get, set } pair scoped to that one key. We&#39;ll call that pair a node.</p><pre>type Node&lt;V&gt; = {<br>  get(): V<br>  set(value: V): void<br>}<br><br>// An observable of an object exposes a node per field;<br>// an observable of a primitive IS a node.<br>type Observable&lt;T&gt; = T extends object<br>  ? { [K in keyof T]: Node&lt;T[K]&gt; }<br>  : Node&lt;T&gt;<br><br>function observable&lt;T&gt;(initialValue: T): Observable&lt;T&gt; {<br>  const isObject = initialValue !== null &amp;&amp; typeof initialValue === &#39;object&#39;<br><br>  const store: Record&lt;string, unknown&gt; = isObject<br>    ? { ...(initialValue as object) }<br>    : { value: initialValue } // box the primitive<br><br>  // Each key gets its own get/set pair.<br>  const node = (key: string): Node&lt;unknown&gt; =&gt; ({<br>    get() {<br>      console.log(`read: ${key}`) // Part 2: remember the reader<br>      return store[key]<br>    },<br>    set(value) {<br>      store[key] = value<br>      console.log(`write: ${key}`) // Part 2: notify subscribers<br>    },<br>  })<br><br>  const proxy = new Proxy(store, {<br>    get(_store, key: string) {<br>      // Primitive: the observable itself IS the value&#39;s node.<br>      if (!isObject) return node(&#39;value&#39;)[key as keyof Node&lt;unknown&gt;]<br>      // Object: every field is its own node.<br>      return node(key)<br>    },<br>  })<br><br>  return proxy as Observable&lt;T&gt;<br>}</pre><p>Now both cases work the same way. A boxed primitive exposes .get() and .set() directly. An object exposes them on each field:</p><pre>// primitive<br>const count$ = observable(0)<br>count$.get() // read: value  → 0<br>count$.set(5) // write: value<br><br>// object: every field is independently trackable<br>const job$ = observable({ status: &#39;queued&#39;, error_message: null })<br>job$.status.get() // read: status  → &#39;queued&#39;<br>job$.status.set(&#39;running&#39;) // write: status<br>job$.error_message.get() // read: error_message → null</pre><p><strong>We dropped the </strong><strong>set trap.</strong> Writes don&#39;t go through the proxy anymore. They go through node.set(). That&#39;s the point, not an accident. If there&#39;s only one way to write a value, there&#39;s only one place that has to announce the change. A stray job$.status = &#39;x&#39; can&#39;t sneak past, because that path doesn&#39;t exist anymore. This is also why Legend State won&#39;t let you assign to a value directly. Raw assignment would skip the one door that knows how to tell anyone.</p><p><strong>We’re only going one level deep, for now.</strong> Right now observable() handles a flat object. If a field holds another object, job$.something.get() just hands it back raw. You can&#39;t keep chaining into job$.something.nested.get(). The real library wraps every level in its own node, so the chaining goes as deep as your data does. We&#39;re not doing that yet, and it&#39;s more than a one-line change. To recurse, a node&#39;s get would have to return another proxy instead of a plain value, and the subscription bookkeeping has to follow all the way down. That&#39;s what Part 5 is for. Until then, staying flat keeps things easy to follow.</p><p>Each key gets its own node, and each node is a separate object closed over its own key. That separation is what makes fine-grained reactivity possible later. Once set starts notifying subscribers in Part 2, calling job$.status.set() will only touch the things that read status. The error_message node won&#39;t hear a thing.</p><p>It’s also why raw assignment had to go. There’s no way to reach a value except through its node’s get and set. That one doorway per key is exactly where we&#39;ll attach the subscription list in Part 2.</p><p>Pay attention at the types. Observable&lt;T&gt; at the top is a conditional type. If T is an object, it maps every key to its own Node&lt;T[K]&gt;. So job$.status is a Node&lt;string&gt;, and job$.status.get() comes back typed as string, fully inferred, with no annotations at the call site. If T is a primitive, the observable itself is a Node&lt;T&gt;. The implementation still deals in unknown on the inside, because a Proxy can&#39;t really be typed from within. So we seal that off with a single assertion at the return. Consumer code never touches the unknown. It just gets typed nodes.</p><h3>This is already TMI I’m guessing, well at least it was for me</h3><p>So this is where we are ending the part 1. What we have now with us is an observable() that notices everything. Every .get() runs a line where we could remember who&#39;s reading. Every .set() runs a line where we could tell them. Right now those lines are just console.logs. The proxy knows when you read a key and when you change it, and it does nothing with that knowledge.</p><p>That gap is the whole difference between a proxy that logs and a signal. Part 2 closes it. We give those two spots real memory: a way to remember exactly which functions read a key, and a way to re-run them, and only them, when that key changes. That’s where observable() stops just logging and does what it’s supposed to do. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d5123399217" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build React components that age like fine wine]]></title>
            <link>https://medium.com/@so_deep.dev/how-to-build-components-that-age-like-fine-wine-and-not-milk-71b63430c70d?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/71b63430c70d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 07:09:02 GMT</pubDate>
            <atom:updated>2026-07-08T07:29:34.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6uwB3z-7hQ6Xw95XC--fQ.png" /></figure><p>If you’ve worked with React for any real amount of time, you’ve almost definitely built (or inherited) a component that tried to do everything. A &lt;Modal&gt; with fifteen boolean props. A &lt;Card&gt; with a variant prop that has eight possible values, each one quietly branching off into its own rendering path inside. It works fine for a while, until someone needs a slightly different modal, and now you&#39;re either adding prop number sixteen or forking the whole thing. Fast forward six months(1 sprint, if you’re working in a startup) and nobody, including you, wants to touch it.</p><p>That’s a component aging like milk. It gets worse every time someone opens the file.</p><p>I’ve shipped my fair share of these, and the fix that finally stuck for me was to stop building one giant component that tries to guess every future need, and instead build a handful of small, focused pieces that snap together into whatever I need. Turns out this has a name, ✨<strong>composability</strong>✨, and once you start seeing it, you can’t unsee it.</p><p>Unless you’re living under a rock, you’ve heard of shad cn by now. It copies components straight into your ui folder as source code, not a package, so every one of those components is something you can freely edit. Open any file it generates and you&#39;ll find Radix or Base UI sitting right there underneath, the primitive libraries actually doing the heavy lifting: focus trapping, keyboard navigation, ARIA roles, all the stuff that&#39;s genuinely painful to get right on your own.</p><p>Ever wondered how those primitives pull this off? Let’s build one ourselves and see what it actually takes to make it work.</p><h3>Let’s build composable tabs primitives</h3><p>Alright, here’s what we’re gonna end up with by the time we’re done:</p><pre>&lt;Tabs.Root defaultValue=&quot;account&quot;&gt;<br>  &lt;Tabs.List&gt;<br>    &lt;Tabs.Trigger value=&quot;account&quot;&gt;Account&lt;/Tabs.Trigger&gt;<br>    &lt;Tabs.Trigger value=&quot;password&quot;&gt;Password&lt;/Tabs.Trigger&gt;<br>  &lt;/Tabs.List&gt;<br>  &lt;Tabs.Content value=&quot;account&quot;&gt;Account settings go here&lt;/Tabs.Content&gt;<br>  &lt;Tabs.Content value=&quot;password&quot;&gt;Password settings go here&lt;/Tabs.Content&gt;<br>&lt;/Tabs.Root&gt;</pre><p>Notice the Tabs. prefix on everything, Tabs.Root, Tabs.List, Tabs.Trigger, Tabs.Content. That&#39;s not just for looks. It&#39;s a way of telling anyone reading the code that these pieces only make sense together. You&#39;re never gonna find a stray Trigger sitting in your codebase with no Tabs around it, the namespace gives that away just from reading the JSX.</p><p>Before we jump into code, let’s quickly talk through what each piece is actually doing:</p><ul><li><strong>Tabs.Root</strong> holds the state, which tab is currently active, and needs to somehow get that info down to its children without us passing props through every level.</li><li><strong>Tabs.List</strong> doesn&#39;t do much on its own, it&#39;s mostly a wrapper for layout and for role=&quot;tablist&quot;.</li><li><strong>Tabs.Trigger</strong> needs to know if it&#39;s the active one, render itself differently if it is, and update the state when clicked.</li><li><strong>Tabs.Content</strong> needs to know the exact same thing, whether it&#39;s the active one, so it knows whether to render at all.</li></ul><p>So we’ve got four components that all need access to the same bit of state, and none of them are directly related as parent and child (well, Trigger and Content definitely aren&#39;t). That&#39;s a textbook case for Context, that&#39;s how we&#39;ll get the state down to every child that needs it. What we put inside that Context is a separate decision though, and that&#39;s what we&#39;ll talk about next.</p><h4>Setting up the store</h4><p>We’re gonna reach for Zustand here instead of plain useState. To be upfront, for something as simple as Tabs, useState inside Context would do the job just fine, there&#39;s really only one value to track. But I want to use Zustand anyway, because the moment your state gets more complicated, multiple interdependent fields, derived values, updates that shouldn&#39;t re-render the whole tree, useState starts to struggle. Building Tabs with Zustand now means you&#39;ve already got the pattern when you actually need it.</p><pre>import { createStore } from &quot;zustand/vanilla&quot;;<br>import { useStore } from &quot;zustand&quot;;<br><br>type TabsState = {<br>  value: string;<br>  setValue: (value: string) =&gt; void;<br>};<br><br>const createTabsStore = (defaultValue: string) =&gt;<br>  createStore&lt;TabsState&gt;((set) =&gt; ({<br>    value: defaultValue,<br>    setValue: (value) =&gt; set({ value }),<br>  }));</pre><p>We’re using createStore from zustand/vanilla instead of the regular create, and the reason is subtler than you&#39;d think. It&#39;s not about avoiding a global store. You could call create inside Tabs.Root too, and each instance would get its own isolated state just fine. The actual difference is what you end up holding: create returns a React hook bound to its store, while createStore returns the bare store object, just getState, setState, and subscribe.</p><p>And since our plan is to pass this thing through Context, that difference matters. Passing a hook around as a value is <a href="https://github.com/pmndrs/zustand/discussions/1975">something the Zustand maintainer explicitly recommends against</a>. Once a hook is sitting in a variable called store, the rules-of-hooks lint can&#39;t see it anymore, and nothing stops someone from calling it conditionally or outside a component. A plain store object is just data, safe to put in Context, pass as a prop, whatever. The hook part comes back later through useStore, called the normal, lintable way.</p><p>To get that store down to the children, we still need Context, just for the store instance itself this time, not the value directly:</p><pre>const TabsStoreContext = createContext&lt;ReturnType&lt;typeof createTabsStore&gt; | null&gt;(null);<br><br>function useTabsStore&lt;T&gt;(selector: (state: TabsState) =&gt; T) {<br>  const store = useContext(TabsStoreContext);<br>  if (!store) {<br>    throw new Error(&quot;Tabs components must be used within Tabs.Root&quot;);<br>  }<br>  return useStore(store, selector);<br>}</pre><p>This is where the two halves come back together. The Context carries the plain store object, and useStore subscribes to it. Notice it takes a selector. A consumer can subscribe to just the slice it cares about and only re-render when that slice changes. On two tabs it doesn&#39;t matter much, but once a component has a lot more going on, it keeps things from re-rendering more than they need to.</p><p>The if (!store) guard is present there to make sure anything using this outside Tabs.Root fails loudly and immediately, instead of chasing a null somewhere downstream.</p><h4>Building Tabs.Root</h4><pre>function Root({ defaultValue, children }: { defaultValue: string; children: ReactNode }) {<br>  const [store] = useState(() =&gt; createTabsStore(defaultValue));<br><br>  return (<br>    &lt;TabsStoreContext.Provider value={store}&gt;<br>      {children}<br>    &lt;/TabsStoreContext.Provider&gt;<br>  );<br>}</pre><p>Tabs.Root is doing less than you might expect, and that&#39;s the point. It creates one store instance and drops it into Context. That&#39;s it. All the actual tab logic lives in the store and the children that read from it.</p><p>The one detail worth pausing on is that the store is created inside useState&#39;s initializer, useState(() =&gt; createTabsStore(defaultValue)), and not as useState(createTabsStore(defaultValue)). The store is constructed exactly once, on mount, with the initializer function. If you wrote it the other way you would be calling createTabsStore on every single render, throwing away the old store (and it’s state) each time.</p><h4>Now, Tabs.List and Tabs.Trigger</h4><p>Tabs.List is the easy one. It doesn&#39;t touch the store at all, it&#39;s just a wrapper that groups the triggers together and carries the right ARIA role:</p><pre>function List({ children, ...props }: ComponentPropsWithoutRef&lt;&quot;div&quot;&gt;) {<br>  return (<br>    &lt;div role=&quot;tablist&quot; {...props}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The role=&quot;tablist&quot; tells a screen reader that the things inside are tabs and should be treated as a set. It&#39;s easy to add now and annoying to retrofit later. This is the kind of unglamorous groundwork the primitive libraries handle for you, and now you&#39;re handling it yourself.</p><p>Tabs.Trigger is where we actually speak with the store:</p><pre>type TriggerProps = ComponentPropsWithoutRef&lt;&quot;button&quot;&gt; &amp; { value: string };<br><br>function Trigger({ value, children, onClick, ...props }: TriggerProps) {<br>  const activeValue = useTabsStore((state) =&gt; state.value);<br>  const setValue = useTabsStore((state) =&gt; state.setValue);<br><br>  const isActive = activeValue === value;<br><br>  return (<br>    &lt;button<br>      role=&quot;tab&quot;<br>      aria-selected={isActive} //accessibility bit<br>      data-state={isActive ? &quot;active&quot; : &quot;inactive&quot;}<br>      onClick={(e) =&gt; {<br>        setValue(value);<br>        onClick?.(e);<br>      }}<br>      {...props}<br>    &gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>We’re pulling value and setValue out of the store with two separate selectors instead of grabbing the whole state in one go. This is that selector thing from earlier, an inactive trigger won&#39;t re-render just because some unrelated piece of state moved.</p><p>The data-state attribute isn&#39;t used for any logic. It&#39;s there so you can style the active tab straight from CSS, without a class-toggling mess in JS:</p><pre>.tabClass[data-state=&quot;active&quot;] {<br>  border-bottom: 2px solid black;<br>}</pre><h4>On to the next one Tabs.Content</h4><p>Tabs.Content follows almost the same shape as Trigger, it reads the active value from the store and compares it against its own value. Here there are two different options in which you might approach the visibility.</p><p><strong>a. Render </strong><strong>null when the value doesn’t match (unmount the inactive tabs)</strong></p><pre>function Content({ value, children }: { value: string; children: ReactNode }) {<br>  const activeValue = useTabsStore((state) =&gt; state.value);<br>  const isActive = activeValue === value;<br><br>  return (<br>    &lt;div role=&quot;tabpanel&quot; hidden={!isActive}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>b. Set hidden as true (Preserves the tabs’ child’s state)</strong></p><pre>function Content({ value, children }: { value: string; children: ReactNode }) {<br>  const activeValue = useTabsStore((state) =&gt; state.value);<br>  const isActive = activeValue === value;<br><br>  return (<br>    &lt;div role=&quot;tabpanel&quot; hidden={!isActive}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>Tying it together with the namespace</h4><p>We’ve got four separate functions, Root, List, Trigger, Content. The last step is bundling them under that Tabs namespace.</p><pre>export const Tabs = {<br>  Root,<br>  List,<br>  Trigger,<br>  Content,<br>};</pre><p>Four components, one shared store, zero props drilled between them. Each piece reads exactly the slice of state it needs and stays completely ignorant of the others.</p><p>The usage we sketched at the very start actually works:</p><pre>&lt;Tabs.Root defaultValue=&quot;account&quot;&gt;<br>  &lt;Tabs.List&gt;<br>    &lt;Tabs.Trigger value=&quot;account&quot;&gt;Account&lt;/Tabs.Trigger&gt;<br>    &lt;Tabs.Trigger value=&quot;password&quot;&gt;Password&lt;/Tabs.Trigger&gt;<br>  &lt;/Tabs.List&gt;<br>  &lt;Tabs.Content value=&quot;account&quot;&gt;Account settings go here&lt;/Tabs.Content&gt;<br>  &lt;Tabs.Content value=&quot;password&quot;&gt;Password settings go here&lt;/Tabs.Content&gt;<br>&lt;/Tabs.Root&gt;</pre><h3>And that’s it!</h3><p>That’s all it takes to build a composable Tabs component from scratch. Four small pieces, one shared store, and not a single prop drilled between them. Each part reads exactly the slice of state it needs and stays completely oblivious to the others. That’s the whole idea behind composability, and it’s the same handful of ideas the primitive libraries you use every day are built on. No magic, just small pieces that combine well.</p><p>The next time you catch yourself about to add one more prop to an already crowded component, pause and ask if that thing wants to be its own piece instead. Your future self, opening this exact file, will thank you for it.</p><p>If you spot any errors in the article or have a question, drop a comment, I’ll get back to you. I hope this helped you build components that age like wine, not milk. Thanks for reading, and have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71b63430c70d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting the Perfect React Project: A Comprehensive Guide to Directory Structure and Essential…]]></title>
            <link>https://blog.stackademic.com/crafting-the-perfect-react-project-a-comprehensive-guide-to-directory-structure-and-essential-9bb0e32ba7aa?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bb0e32ba7aa</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[directory-structure]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[data-fetching]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 16:35:53 GMT</pubDate>
            <atom:updated>2024-02-27T02:16:28.687Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crafting the Perfect React Project: A Comprehensive Guide to Directory Structure and Essential Libraries</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvwBz9tKXCuak4Uhaq14yg.png" /></figure><p><strong>Hello there, ✨beautiful people on the internet✨</strong>! As I navigate the landscape of React development, I’ve come to realize that crafting the perfect project structure and choosing the right libraries is a deeply personal journey. Influenced by my own preferences, project requirements, and evolving best practices, I’m excited to share insights on achieving an excellent developer experience, especially for larger projects.</p><p>While my focus is primarily on React applications, these principles can seamlessly be adopted for projects using frameworks like next, remix, etc. Join me on this subjective exploration as we aim to create a React setup that brings joy to developers tackling more extensive, complex tasks. Remember, opinions may differ, and the best choice ultimately depends on your specific project needs and personal preferences.</p><h3>Starter Templates: Picking the Perfect Bundler for React Development</h3><p>In creating the ideal React development setup, the initial pivotal choice is the selection of the starter template. Upon comparing the widely-used Create React App (CRA) template, which utilizes webpack, with the Vite template, powered by Vite for bundling, the Vite template emerges as the preferred choice. Its advantages, coupled with my dedication to improving developer experience, render it a compelling option. Additionally, to enhance the development environment further, I’ll integrate TypeScript for robust type-checking and enhanced tooling support.</p><h3>Organizing for Efficiency: Establishing Your React Project’s Directory Structure</h3><p>A small precursor to setting the directory structure, let’s first establish the file naming convention. Let’s use kebab case for file names to prevent potential path conflicts. While Unix (Mac) ignores casing in file/directory names, GNU/Linux systems (where the app might be hosted) are case-sensitive. In Unix, ‘NavBar.tsx’ and ‘Navbar.tsx’ are treated the same, but in GNU/Linux, they are considered distinct.</p><p>With that in mind, let’s get to the directory structure. Here’s an output of tree on src for the project I’ve set up.</p><pre>src<br>├── assets<br>│   └── react.svg<br>├── components<br>│   └── global-component<br>│       ├── index.tsx<br>│       └── styles.modules.css<br>├── constants<br>│   ├── local-storage-keys.ts<br>│   └── query-keys.ts<br>├── features<br>│   ├── module-1<br>│   │   ├── components<br>│   │   │   └── user-card<br>│   │   │       ├── index.tsx<br>│   │   │       └── styles.module.css<br>│   │   ├── constants<br>│   │   │   └── module-specific.ts<br>│   │   ├── queries<br>│   │   │   └── use-get-data.tsx<br>│   │   ├── routes<br>│   │   │   └── nested-routes.tsx<br>│   │   ├── stores<br>│   │   │   └── module-specific.ts<br>│   │   ├── index.tsx<br>│   │   └── styles.module.css<br>│   └── module-2<br>├── hooks<br>│   └── use-debounce.ts<br>├── layouts<br>│   ├── navbar.tsx<br>│   └── sidebar.tsx<br>├── queries<br>│   └── use-global-query.ts<br>├── routes<br>│   └── index.tsx<br>├── stores<br>│   └── global-store.ts<br>├── utils<br>│   └── parse-data.tsx<br>├── wrappers<br>│   └── auth-wrapper.tsx<br>├── vite-env.d.ts<br>├── main.tsx<br>├── index.css<br>├── App.css<br>└── App.tsx</pre><p>This directory structure follows a <em>recursive</em> style. Let me provide a detailed explanation of what I mean. assets, components, features, constants, hooks, layouts, queries, routes, stores, utils, wrappers represent directories at the source (src) level:</p><ul><li><strong>assets : </strong>Hosts static assets such as images or icons used across the application, promoting a centralized and easily accessible repository for visual elements.</li><li><strong>components: </strong>Holds global components that are commonly used through out the project. for example, buttons, modals, alerts, etc.</li><li><strong>layouts: </strong>Holds global components responsible for framing the screen layout. These components may utilize the &lt;Outlet /&gt; component from the react-router-dom library for dynamic rendering based on the current route.</li><li><strong>wrappers:</strong> Holds components responsible for wrapping specific functionalities, aiding in the implementation of higher-order components or specialized wrappers for particular features.</li><li><strong>queries: </strong>We’ll revisit this folder when we discuss the ‘react-query’ library.</li><li><strong>features:</strong> Among these src level folders, features stands out with its distinctive pattern, as you’ll observe similar subfolders inside modules within the features directory. This emphasizes the <em>recursive</em> nature of the structure, as previously mentioned.</li></ul><p>The rest of the directories are quite self-descriptive in their purposes.</p><h4>An additional step for beautifying imports</h4><p>To enhance clarity and eliminate cumbersome imports such as ‘../../../components/header,’ using path aliases becomes essential. By employing aliases, you can express the import as ‘@/components/header,’ resulting in a more straightforward and clearer syntax. To implement this improvement, it requires updates to two configuration files.</p><ul><li>vite.config.ts</li></ul><p>As this configuration requires both the path and url, and considering this is a TypeScript project, the inclusion of @types/node is necessary. Prior to making modifications to ‘vite.config.ts,’ ensure you install these dev dependencies by running the following command.</p><pre>npm i -D path url @types/node</pre><p>And this is what the modified config will look like</p><pre>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br><br>import path from &#39;path&#39;<br>import url from &#39;url&#39;<br><br>const __filename = url.fileURLToPath(import.meta.url);<br>const __dirname = path.dirname(__filename);<br><br>// https://vitejs.dev/config/<br>export default defineConfig({<br>  // ... other config<br>  resolve: {<br>    alias: {<br>      &#39;@&#39;: path.resolve(__dirname, &#39;./src&#39;),<br>      &#39;@components&#39;: path.resolve(__dirname, &#39;./src/components&#39;),<br>      &#39;@routes&#39;: path.resolve(__dirname, &#39;./src/routes&#39;),<br>      &#39;@store&#39;: path.resolve(__dirname, &#39;./src/store&#39;),<br>      &#39;@utils&#39;: path.resolve(__dirname, &#39;./src/utils&#39;),<br>      &#39;@assets&#39;: path.resolve(__dirname, &#39;./src/assets&#39;),<br>      &#39;@features&#39;: path.resolve(__dirname, &#39;./src/features&#39;),<br>      &#39;@hooks&#39;: path.resolve(__dirname, &#39;./src/hooks&#39;),<br>      &#39;@wrappers&#39;: path.resolve(__dirname, &#39;./src/wrappers&#39;),<br>      // and so on<br>    },<br>  },<br>  plugins: [react()],<br>})</pre><ul><li>TypeScript also needs to know the aliases so the second file to be modified is typescript.json</li></ul><pre>{<br>    &quot;compilerOptions&quot;: {<br>    // ... rest of the config<br>    &quot;baseUrl&quot;: &quot;.&quot;,<br>    &quot;paths&quot;: {<br>      &quot;@/*&quot;: [&quot;src/*&quot;],<br>      &quot;@components/*&quot;: [&quot;src/components/*&quot;],<br>      &quot;@routes/*&quot;: [&quot;src/routes/*&quot;],<br>      &quot;@store/*&quot;: [&quot;src/store/*&quot;],<br>      &quot;@utils/*&quot;: [&quot;src/utils/*&quot;],<br>      &quot;@assets/*&quot;: [&quot;src/assets/*&quot;],<br>      &quot;@features/*&quot;: [&quot;src/features/*&quot;],<br>      &quot;@hooks/*&quot;: [&quot;src/hooks/*&quot;],<br>      &quot;@wrappers/*&quot;: [&quot;src/wrappers/*&quot;],<br>      // and so on<br>    }<br>  },<br>  &quot;include&quot;: [&quot;src&quot;],<br>  &quot;references&quot;: [{ &quot;path&quot;: &quot;./tsconfig.node.json&quot; }]<br>}</pre><p>With these configurations set up, developers can leverage the path aliases, bringing the codebase one step closer to achieving the ultimate developer experience.</p><h3>Enhancing Development Flow: Essential Tooling with Prettier, ESLint and Husky</h3><p>Prettier is an automatic code formatter that ensures every piece of code adheres to a consistent style by applying predefined formatting rules. This tool eliminates discrepancies in coding styles among developers, making the codebase cleaner and easier to read.</p><p>ESLint serves as a code analysis tool that enforces coding standards and identifies problematic patterns. It helps maintain code quality and prevents common errors by adhering to best practices outlined in its configuration.</p><p>Husky introduces pre-commit hooks to the development workflow, automating the process of code verification before commits are made. By integrating with tools like Prettier and ESLint, Husky ensures that every commit meets the project’s coding standards, enhancing overall code integrity.</p><p>Setting up these tools deserves its own guide, but the linked YouTube video gives a detailed explanation on how to do it. Use the video for guidance on setting up ESLint and Prettier, but not for Husky, as it doesn’t include ‘lint-staged’ in its setup.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZXW6Jn6or1w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZXW6Jn6or1w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZXW6Jn6or1w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/faa89d6cfda997cf8f4943bd4ee41b5a/href">https://medium.com/media/faa89d6cfda997cf8f4943bd4ee41b5a/href</a></iframe><p>Check out this video for a detailed guide on setting up Husky with ‘lint-staged’. Note, though, that it’s tailored for JavaScript projects, so you may need to adjust the setup for TypeScript.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_ssKvmZqSnk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_ssKvmZqSnk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_ssKvmZqSnk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d97c63e9b3d3e9acf24144eb9c7a5244/href">https://medium.com/media/d97c63e9b3d3e9acf24144eb9c7a5244/href</a></iframe><h3>Core Libraries: Facilitating Smoother Development with Effortless Configuration and Reduced Duplication</h3><p>Once the tools are set and the folders are organized, the next big step is choosing the right libraries for managing data and state. These choices are key to making a React project work well and making it easier for developers to build and maintain.</p><h4>Zustand for State Management</h4><p><a href="https://docs.pmnd.rs/zustand/getting-started/introduction">Zustand</a> is a minimalist state management library designed for React and other JavaScript applications. It stands out for its simplicity and ease of use, offering a straightforward way to create and manage global state without the complexity of more traditional state management solutions. Zustand eliminates the need for boilerplate code, enabling developers to set up a global store with just a few lines of code. Its API is based on hooks, making it a natural fit for React projects. Zustand supports asynchronous actions and middleware, allowing for flexible state updates and enhancing the development experience with efficient state management practices.</p><p>Here’s a quick example on how to create a zustand store and consume it in a react component</p><p><strong>Store Creation</strong></p><pre>import create from &#39;zustand&#39;;<br><br>interface CounterState {<br>  count: number;<br>  increment: () =&gt; void;<br>  decrement: () =&gt; void;<br>}<br><br>const useStore = create&lt;CounterState&gt;((set) =&gt; ({<br>  count: 0, // initial state<br>  increment: () =&gt; set((state) =&gt; ({ count: state.count + 1 })),<br>  decrement: () =&gt; set((state) =&gt; ({ count: state.count - 1 })),<br>}));</pre><p><strong>Consuming</strong></p><pre>import React from &#39;react&#39;;<br>import { useStore } from &#39;./store&#39;; // Adjust the import path according to your file structure<br><br>const Counter: React.FC = () =&gt; {<br>  const { count, increment, decrement } = useStore();<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;+&lt;/button&gt;<br>      &lt;button onClick={decrement}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>Check out this excellent video showcasing how easy it is to handle asynchronous actions, illustrating why this library is a top choice for seamless state management.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_ngCLZ5Iz-0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_ngCLZ5Iz-0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_ngCLZ5Iz-0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7895df0618189dd757392d8949eaed8/href">https://medium.com/media/a7895df0618189dd757392d8949eaed8/href</a></iframe><h4>React Query for Data Fetching</h4><p>React Query stands out as an optimal library for data fetching in React applications due to its powerful features and efficiency in handling server state. Unlike traditional state management libraries that are often used to manage both UI state and server (or API) state, React Query specializes in synchronizing asynchronous data from external sources, such as APIs, with your application’s UI. This specialization offers several key benefits:</p><ol><li><strong>Automatic Caching and Background Updates</strong>: React Query automatically caches fetched data, reducing the number of requests to the server and improving the user experience by instantly providing data from cache where applicable. It also supports background data fetching to ensure the user interface is always up-to-date with the latest server state without manual intervention.</li><li><strong>Built-in Data Synchronization</strong>: It handles data synchronization tasks, such as refetching data when a component remounts or after a specified interval, making it easier to keep the UI consistent with external data sources.</li><li><strong>Simplified Data Management</strong>: By focusing on server state, React Query eliminates the need for boilerplate code often associated with managing API data in global state management stores. Developers can query, mutate, and manage server data with minimal setup, streamlining the development process.</li><li><strong>DevTools for Enhanced Debugging</strong>: React Query comes with DevTools that provide insights into queries and mutations, making it easier to debug and optimize data fetching strategies.</li></ol><p>Using React Query can, in many cases, negate the necessity for a traditional state management library, especially if the primary use case for such a library was to store and manage API data. Since React Query efficiently handles data fetching, caching, and synchronization, it reduces the complexity of managing server state.</p><p>For a quick and thorough understanding of React Query, check out the crash course video by WebDevSimplified. It’s a great resource to get up to speed with how React Query works and how it can benefit your React projects.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fr8Dg0KVnfMA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dr8Dg0KVnfMA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fr8Dg0KVnfMA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/314791a403fa725958b1b7d80b4e4c44/href">https://medium.com/media/314791a403fa725958b1b7d80b4e4c44/href</a></iframe><h3>Final Touch: Ensuring Everything Stays Aligned</h3><p>If you’re the sole developer on this project, you’ve set yourself up for a smooth coding journey. However, if you have other contributors, it’s crucial they adhere to the established standards. To ensure consistency doesn’t slip through the cracks, there’s one more addition that can help maintain consistency across the contributions.</p><p>A pull request (PR) template, it can play a pivotal role in maintaining consistency and order when multiple contributors are involved in a project. It serves as a checklist or guide that every contributor must follow when submitting their code for review and also the things a reviewer might need to verify before approving the PR. Here’s a template I use</p><ul><li>Paste this inside project-root/.github/pull_request_template.md</li></ul><pre>**Description:**<br>Provide a concise summary of the changes introduced by this pull request.<br><br>**Related Issues:**<br>- Fixes #IssueNumber<br>- Addresses #IssueNumber<br><br>**Changes:**<br>List the main changes introduced by this pull request.<br><br>- [ ] Change 1<br>- [ ] Change 2<br>- [ ] ...<br><br>**Screenshots / GIFs (if applicable):**<br>Include visual representations of the changes, if relevant.<br><br>**Testing:**<br>Describe the steps to test the changes made in this pull request.<br><br>1. Step 1<br>2. Step 2<br>3. ...<br><br>**Checklist:**<br>Ensure that you have completed the following tasks:<br><br>- [ ] The code builds successfully without errors or warnings.<br>- [ ] All existing tests pass.<br>- [ ] New features are accompanied by appropriate tests.<br>- [ ] Updated documentation, if applicable.<br>- [ ] Code follows the project&#39;s coding guidelines.<br><br>**Additional Comments:**<br>Any additional information or context you would like to provide.<br><br>---<br><br>**Reviewer Checklist:**<br>Reviewers, please make sure the following points are addressed before approving the pull request:<br><br>- [ ] Code readability and maintainability.<br>- [ ] Adherence to coding standards and best practices.<br>- [ ] Test coverage and the successful passing of tests.<br>- [ ] Documentation updates, if applicable.</pre><h3>That’s all for today folks…</h3><p>Before we wrap up, it’s important to highlight how the careful selection of core libraries and the thoughtful setup of directory structures significantly contribute to improving Developer Experience (DX). By choosing the right libraries that fit the project’s goals and organizing the code in a clear, logical way, developers pave the way for smoother and more efficient development processes. This approach not only enhances workflow efficiency but also simplifies onboarding for new team members, ensuring they can easily navigate and contribute to the project. These strategic decisions are key in elevating productivity, minimizing errors, and maintaining the scalability and manageability of the project, thereby elevating the overall DX.</p><p>This blog reflects my personal journey with React development, offering insights drawn from my own experiences and choices. It’s meant to serve as inspiration, encouraging you to adapt and refine your React practices to best suit your team’s and your own development style, aiming for a process that’s both productive and fulfilling.</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=9bb0e32ba7aa" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/crafting-the-perfect-react-project-a-comprehensive-guide-to-directory-structure-and-essential-9bb0e32ba7aa">Crafting the Perfect React Project: A Comprehensive Guide to Directory Structure and Essential…</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[Non-fungible tokens(NFT) for user auth in web 2 apps]]></title>
            <link>https://medium.com/cryptostars/non-fungible-tokens-nft-for-user-auth-in-web-2-apps-5a6a758afe5?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a6a758afe5</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[ethersjs]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Sat, 22 Jan 2022 07:00:16 GMT</pubDate>
            <atom:updated>2022-01-28T12:10:04.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnld4EM4Jpsr3kH919Gicw.png" /></figure><p>Hi there, awesome human on the internet! GM✨! In this blog, we are going to be coding an authentication system that gives users access if they happen to hold an NFT in the wallet they sign in with. This is somewhat an intersection of web2 and web3. In this tutorial, we will be leveraging EVM-compatible blockchains. Below are the pre-requisites to follow along.</p><ul><li>Basic Solidity.</li><li>express.js, JWT, and javascript.</li><li>Familiarity with an EVM-compatible crypto wallet like metamask.</li></ul><p>In this article, I’ll only be explaining the key aspects of the implementation rather than going deep into each and every line of the code. If you want the complete implementation, please click <a href="https://github.com/sudeepgumaste/nft-auth">here</a></p><h3>Signed messages</h3><p>This is the key piece of the puzzle in our implementation. To check if the user who has made a request to the API holds at least one of our NFTs, we need to know their public address but since the blockchain is a public ledger anyone can fraudulently claim that they hold the keys to a public address. We need a way to be able to verify the claim.</p><p>That’s where the magical cryptographic signature comes into play! A person can sign a message with their private key (without revealing it!) and give the signed message along with the original message to a verifier. Verifier can verify a signature against a message, arrive at the public key, and then derive the address from the public key and be sure of it that signer actually holds private keys to the address they claim to be the owner of.</p><h3>Signing a message on frontend</h3><p>The signing step will happen on the client-side with the help of web3 provider injected by any wallet extensions like metamask. To get a user to sign a message, you can use the following snippet</p><pre>// this function generates the message the frontend needs to sign<br>const constructMessage = (timestamp: number, address: string) =&gt; `<br>This request will not trigger a blockchain transaction or cost any gas fees.</pre><pre>Your authentication status will reset after 24 hours.</pre><pre>Address:${address}</pre><pre>Timestamp:${timestamp}<br>`;</pre><pre>// this function returns signature and the original message<br>const signMessage = async () =&gt; {<br>    const { ethereum } = window; <br>    const provider = new ethers.providers.Web3Provider(ethereum);<br>    const signer = provider.getSigner();</pre><pre>    const timestamp = Math.floor(Date.now() / 1000);<br>    const address = await signer.getAddress();<br>    const message = constructMessage(timestamp, address);</pre><pre>    const signature = await signer.signMessage(message);</pre><pre>    return [signature, message]<br>  };</pre><p>Notice that the message includes a timestamp. This is used to avoid using the same signature repeatedly. With the signature and message generated in the above function make an API call to the backend.</p><h3>Verifying the signature on the backend</h3><p>Once the message is signed and both message and signature passed to the backend, you can verify the signature to arrive at the public address. Below is the code snippet of implementing the verification for auth as an express.js controller function.</p><pre>// this function verifies signature and returns a JWT for further auth<br>const login = async (req, res) =&gt; {<br>  const { message, signature } = req.body;</pre><pre>  // extract address timestamp from message<br>  const [addressElement, timestampElement] = message.split(&quot;\n\n&quot;).slice(&quot;-2&quot;);<br>  const timestamp = timestampElement.split(&quot;:&quot;)[1];<br>  const address = addressElement.split(&quot;:&quot;)[1];</pre><pre>  // verify timestamp not older than 5 minutes<br>  const now = Math.floor(Date.now() / 1000);<br>  if (now - timestamp &gt; 300) {<br>    return res.status(401).json({<br>      message: &quot;Bro... this time stamp old af&quot;,<br>    });<br>  }</pre><pre>  const hashMessage = ethers.utils.hashMessage(message);<br>  const pk = ethers.utils.recoverPublicKey(hashMessage, signature);<br>  const recoveredAddress = ethers.utils.computeAddress(pk);</pre><pre>  if (recoveredAddress !== address) {<br>    return res.status(401).json({<br>      message: &quot;Bro... this signature is not for you&quot;,<br>    });<br>  }</pre><pre>  // if you plan on just implementing login with ethereum<br>  // issue your JWT here</pre><pre>  // making a smart contract call to check if the address holds your NFTs<br>  const nfts = await nfKeyContract.getNftsByAddress(recoveredAddress);<br>  if (nfts.length === 0) {<br>    res.status(401).json({<br>      message: &quot;Buy NFKey to access this resource&quot;,<br>    });<br>  }</pre><pre>  // construct jwt token<br>  const accessToken = jwt.sign(<br>    { address, nftCount: nfts.length },<br>    process.env.JWT_SECRET,<br>    {<br>      expiresIn: &quot;24h&quot;,<br>    }<br>  );</pre><pre>  res.json({<br>    jwt: accessToken,<br>  });<br>}; </pre><h3>NFT smart contract</h3><p>You can find numerous tutorials on how to create an NFT smart contract with solidity. If you’re not familiar with the standard NFT smart contract, I’d suggest you go through the NFT track on <a href="https://app.buildspace.so/projects/CO961ddb5f-f428-4608-9949-a9a2f461eb3f">buildspace ✨</a>. Apart from the standard contract, I’ve added a function that returns an array of NFT ids an address holds for our convenience at the later stage.</p><pre>function getNftsByAddress(address walletAddress)<br>    external<br>    view<br>    returns (uint256[] memory)<br>{<br>    uint256 nfKeysCount = balanceOf(walletAddress);<br><br>    uint256[] memory nfKeys = new uint256[](nfKeysCount);<br>    uint256 currentIndex = 0;<br><br>    for (uint256 i = 0; i &lt; _tokenIds.current(); i++) {<br>        if (ownerOf(i) == walletAddress) {<br>            nfKeys[currentIndex] = i;<br>            currentIndex++;<br>        }<br>    }<br>    return nfKeys;<br>}</pre><p>Of course, this function is not required and you can do the processing on the backend as well but I prefer to do it in the smart contract</p><p>That’s all for the article folks. Thanks for reading. I hope this helped you. If I’ve made any mistakes please let me know in the comments, I’ll make sure to fix them. And if you have any questions, make sure to leave them in the comments as well, I’ll try to answer them to the best of my abilities. Have a great day!</p><p>Originally published on <a href="https://sudeepgumaste.hashnode.dev/nft-for-user-auth-in-web-2-apps">Hashnode</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a6a758afe5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cryptostars/non-fungible-tokens-nft-for-user-auth-in-web-2-apps-5a6a758afe5">Non-fungible tokens(NFT) for user auth in web 2 apps</a> was originally published in <a href="https://medium.com/cryptostars">CryptoStars</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s code a Reaction component in React]]></title>
            <link>https://medium.com/@so_deep.dev/lets-code-a-reaction-component-in-react-c71bb78a15?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c71bb78a15</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Tue, 15 Sep 2020 18:51:03 GMT</pubDate>
            <atom:updated>2020-09-15T18:51:03.860Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YM6VscJgrDvx8Ts_" /></figure><p>We are gonna code a reaction component with following features</p><ul><li>User clicks on the button to trigger the reaction bar and the reaction bar closes onclicking on the button again.</li><li>User can click on one of the reactions to react and this action closes the reactions bar after setting the reaction.</li><li>If already reacted, and user clicks on the button, the reaction is reset</li></ul><blockquote><em>This project was bootstrapped with create-react-app and please make sure to install node-sass if you’re following along</em></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ftxkri&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Ftxkri&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ftxkri%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b346a6bd62b9fd7c878033077036cd15/href">https://medium.com/media/b346a6bd62b9fd7c878033077036cd15/href</a></iframe><h3>Let’s begin with JS</h3><p><strong>ReactionButton.jsx</strong></p><pre>import React, { useState } from &quot;react&quot;;</pre><pre>import { ReactComponent as Crying } from &quot;../../assets/crying.svg&quot;;<br>import { ReactComponent as Sad } from &quot;../../assets/sad.svg&quot;;<br>import { ReactComponent as Happy } from &quot;../../assets/happy.svg&quot;;<br>import { ReactComponent as Happy2 } from &quot;../../assets/happy-2.svg&quot;;<br>import { ReactComponent as Love } from &quot;../../assets/in-love.svg&quot;;<br>import { ReactComponent as NoReaction } from &quot;../../assets/no-reaction.svg&quot;;</pre><pre>import &quot;./reaction-button.scss&quot;;</pre><pre>const ReactionButton = ({ state, setState }) =&gt; {<br>  const [isTriggered, setIsTriggered] = useState(false);</pre><pre>const reactions = [&lt;Crying /&gt;, &lt;Sad /&gt;, &lt;Happy /&gt;, &lt;Happy2 /&gt;, &lt;Love /&gt;];</pre><pre>return (<br>    &lt;div className=&quot;reaction-button&quot;&gt;<br>      &lt;button<br>        className={`reaction-button__trigger ${<br>          isTriggered ? &quot;reaction-button__trigger--active&quot; : &quot;&quot;<br>        }`}<br>        type=&quot;button&quot;<br>        onClick={() =&gt; {<br>          if (state === null) {<br>            setIsTriggered((val) =&gt; !val);<br>          } else {<br>            setState(null);<br>          }<br>        }}<br>      &gt;<br>        {state !== null ? reactions[state] : &lt;NoReaction /&gt;}<br>      &lt;/button&gt;<br>      &lt;div<br>        className={`reaction-button__reactions ${<br>          isTriggered ? &#39;reaction-button__reactions--active&#39; : &#39;&#39;<br>        }`}<br>      &gt;<br>        {reactions.map((reaction, index) =&gt; (<br>          &lt;button<br>            key={index}<br>            className=&quot;reaction-button__reactions__reaction&quot;<br>            onClick={() =&gt; {<br>              setState(index);<br>              setIsTriggered(false);<br>            }}<br>          &gt;<br>            {reaction}<br>          &lt;/button&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>ReactionButton.defaultProps = {<br>  state: null<br>};</pre><pre>export default ReactionButton;</pre><p>Going over the code, I’ve imported useState (we’ll be using hooks to manage the state) followed by asset imports and scss file import(we’ll go over that as well in a short while).</p><pre>const ReactionButton = ({ state, setState }) =&gt; {</pre><p>Notice that the actual reaction state and its corresponding setState function will be passed as props from the parent component as there is no easy way to pass back the state from child to the parent.</p><pre>const [isTriggered, setIsTriggered] = useState(false);</pre><p>We’re gonna be using isTriggered as a state variable to add and remove a class to our reactions bar from where the user is gonna be clicking on a reaction. The default state is set to false.</p><pre>const reactions = [&lt;Crying /&gt;, &lt;Sad /&gt;, &lt;Happy /&gt;, &lt;Happy2 /&gt;, &lt;Love /&gt;];</pre><p>This line is gonna create an array of React.createElement calls for mounting <a href="https://www.flaticon.com/packs/emoticons-4?word=emoji">SVGs</a> that I’ve imported.</p><pre>      &lt;button<br>        className={`reaction-button__trigger ${<br>          isTriggered ? &quot;reaction-button__trigger--active&quot; : &quot;&quot;<br>        }`}<br>        type=&quot;button&quot;<br>        onClick={() =&gt; {<br>          if (state === null) {<br>            setIsTriggered((val) =&gt; !val);<br>          } else {<br>            setState(null);<br>          }<br>        }}<br>      &gt;<br>        {state !== null ? reactions[state] : &lt;NoReaction /&gt;}<br>      &lt;/button&gt;</pre><p>Then starts the markup. The component is enclosed in a div with a className of reaction-button. The immediate child, button, has a class of reaction-button__trigger [ I&#39;m using BEM conventions for naming the classes. Let&#39;s talk about it some other day ;) ]. On clicking the button, isTriggered is toggled and depending on the value of isTriggered, reaction-button__trigger--active is added to the classList. If the user has already reacted, the reaction is set to null. The reaction displayed in the button body is also conditionally rendered. If there&#39;s no reaction, a default emoji is rendered and one of the reactions is rendered otherwise.</p><pre>      &lt;div<br>        className={`reaction-button__reactions ${<br>          isTriggered ? &#39;reaction-button__reactions--active&#39; : &#39;&#39;<br>        }`}<br>      &gt;<br>        {reactions.map((reaction, index) =&gt; (<br>          &lt;button<br>            key={index}<br>            className=&quot;reaction-button__reactions__reaction&quot;<br>            onClick={() =&gt; {<br>              setState(index);<br>              setIsTriggered(false);<br>            }}<br>          &gt;<br>            {reaction}<br>          &lt;/button&gt;<br>        ))}<br>      &lt;/div&gt;</pre><p>Next comes the reaction bar. This div has a className of reaction-button__reactions and if isTriggered is set to true, reaction-button__reactions--active gets added to its classList. This class is gonna help us show and hide the bar. Within this div, we have the reaction buttons with the className reaction-button__reactions__reaction. We are looping through the reactions array to populate the div. On clicking one of these buttons, we are gonna set the reaction index and close the reaction bar.</p><h3>Let’s style it!</h3><p><strong>reaction-button.scss</strong></p><pre><a href="http://twitter.com/import">@import</a> &#39;../../sass/base.scss&#39;;</pre><pre>.reaction-button{<br>  position: relative;<br>  &amp;__trigger{<br>    padding: 0.5rem 1rem;<br>    background: none;<br>    border: none;<br>    border-radius: 1rem;<br>    transition: background 300ms ease;</pre><pre>    &amp;--active,&amp;:hover{<br>      background: #e8eaf6;<br>    }</pre><pre>    svg{<br>      width: 24px;<br>      height: 24px;<br>    }<br>  }</pre><pre>  &amp;__reactions{<br>    display: flex;<br>    position: absolute;<br>    top: calc(100% + 0.5rem);<br>    left: 0;<br>    padding: 0.5rem;<br>    border-radius: 1rem;<br>    box-shadow: 4px 4px 15px rgba(0, 0, 0, 0.1);<br>    transform: scale(0);<br>    transform-origin: top left;<br>    transition: transform 300ms ease;<br>    background: #fff;</pre><pre>    &amp;--active{<br>      transform: scale(1);<br>    }</pre><pre>    &amp;__reaction{<br>      padding: 0.5rem 1rem;<br>      background: none;<br>      border: none;<br>      border-radius: 1rem;<br>      transition: background 300ms ease;<br>      margin: 0.25rem;</pre><pre>      &amp;:hover{<br>        background: #e8eaf6;<br>      }</pre><pre>      svg{<br>        width: 24px;<br>        height: 24px;<br>      }<br>    }<br>  }<br>}</pre><p>base.scss contains some rules to remove the default styling applied by the browsers.</p><pre>.reaction-button{ <br>  position: relative;<br>}</pre><p>Coming to the styles that matter, reaction-button class has a position: relative because we&#39;ll be setting the position of reaction-button__reaction as absolute with respect to this class.</p><pre>&amp;__trigger{ padding: 0.5rem 1rem; background: none; border: none; border-radius: 1rem; transition: background 300ms ease; &amp;--active,&amp;:hover{ background: #e8eaf6; } svg{ width: 24px; height: 24px; } }</pre><p>Next comes the styles for the reaction-button__trigger.There&#39;s nothing much to explain here, just some properties to make the button look pretty. When reaction-button__trigger--active is applied or the user hovers over the button, it gets a very light shade of blue applied to it.</p><p>There are couple of things to note here. First,</p><p>This makes the bar appear right below the button. Second,</p><ul><li>transform: scale(0) hides the component by shrinking it and when reaction-button__trigger--active is applied, this gets overridden with transform: scale(1) and this brings the component to its normal size.</li><li>transform-origin: top left makes the component scale from top-left. By default, it would have scaled from the center.</li><li>transition: transform 300ms ease makes sure the sweet interaction takes its time.</li></ul><p>That’s it! We did it. That’s all it takes to code this amazing component! I hope you enjoyed reading this and I hope this helped you. Thanks for stopping by and reading. Have a great day!</p><blockquote><em>P.S : I’m creating a </em><a href="https://github.com/sudeepgumaste/MyReactComponents"><em>react component library</em></a><em> and this is one of many awesome components that are going to be added.</em></blockquote><p><em>Originally published at </em><a href="https://sudeepgumaste.hashnode.dev/lets-code-a-reaction-component-in-react"><em>https://sudeepgumaste.hashnode.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c71bb78a15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Code a Dope Animated Loader With CSS]]></title>
            <link>https://medium.com/swlh/lets-code-a-dope-loader-with-css-c2d48e31050d?source=rss-c585f7ee303d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2d48e31050d</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css-animation]]></category>
            <dc:creator><![CDATA[Sudeep Gumaste]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 17:47:43 GMT</pubDate>
            <atom:updated>2020-09-04T22:11:48.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aKHEywcDpoYRi8AF" /><figcaption>Photo by <a href="https://unsplash.com/@florianolv?utm_source=medium&amp;utm_medium=referral">Florian Olivo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsudeepgumaste%2Fembed%2Fpreview%2FabdrorB%3Fheight%3D600%26slug-hash%3DabdrorB%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsudeepgumaste%2Fpen%2FabdrorB&amp;image=https%3A%2F%2Fassets.codepen.io%2F3409340%2Finternal%2Fscreenshots%2Fpens%2FabdrorB.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dtrue%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1598031136%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/45f7ca35a58caf28947f16745f133358/href">https://medium.com/media/45f7ca35a58caf28947f16745f133358/href</a></iframe><p>Hey there amazing human! I came across this dope loader animation a while ago and I thought I should code that. Today in this blog post, we’re gonna code that together! Sounds interesting? Then lest’s jump right into it!</p><h3><strong>Starter code</strong></h3><p>This is the initial code that we’re gonna be starting with</p><h4>Starter HTML</h4><pre>&lt;div class=&quot;box&quot;&gt;<br>  &lt;div class=&quot;container&quot;&gt;<br>    &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>    &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><h4>Starter CSS</h4><pre>/* I don&#39;t like the default styles applied by the browsers */<br>*, *::before, *::after{<br>  margin: 0;<br>  padding: 0;<br>  box-sizing: border-box;<br>}<br><br>body{<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>  width: 100vw;<br>  height: 100vh;<br>  background: #c5cae9;<br>}<br><br>.box {<br>  width: 300px;<br>  height: 300px;<br>  background: #1a237e;<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>  box-shadow: 4px 4px 20px rgba(0, 0, 0, 0.3);<br>}<br><br>.container {<br>  height: 15px;<br>  width: 105px;<br>  display: flex;<br>}<br><br>.container .circle {<br>  width: 15px;<br>  height: 15px;<br>  border-radius: 50%;<br>  background-color: #fff;<br>  margin-right: 30px;<br>}</pre><p>This should result in something that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*F2hSLeWhGJm0Sd_E" /></figure><p>Yes, there are just two circles for now</p><h3>Let’s get movin</h3><p>Let us now start by moving these circles to the right. In order to do that we’ll need a keyframe animation.</p><pre>@keyframes move {<br>  from {<br>    transform: translateX(0px);<br>  }<br>  to {<br>    transform: translateX(45px);<br>  }<br>}</pre><p>The code is pretty straight forward. We are starting from 0px and moving the circles 45px(15px + 30px margin) to the right. We’re using <em>transform</em> to move the circles. You could also use left with couple of extra steps but it’s better to use transform performance wise.</p><p>Now that we’ve coded a keyframe animation, let’s apply it to the circles.</p><pre>.container .circle {<br>  width: 15px;<br>  height: 15px;<br>  border-radius: 50%;<br>  background-color: #fff;<br>  margin-right: 30px;<br>  /* added line */<br>  animation: move 500ms linear 0ms infinite;<br>}</pre><p>In animation property, we’ll mention the animation name and other attributes. Let’s break down this line.</p><ul><li>The keyframe’s name is move</li><li>Animation duration is 500 mili seconds</li><li>The timing function is linear</li><li>There’s a delay of 0ms</li><li>The number of iterations are infinite</li></ul><p>AND we have the two moving circles! The first step is done!</p><h3>Grow and shrink</h3><p>Now on to the next step, we need to make the first circle look like it’s coming from behind or make it look like it’s growing. For that, we need to add a circle to our html, inside the container div</p><pre>  &lt;!-- added line --&gt;<br>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;</pre><p>To achieve the desired effect we need to position it absolutely with respect to the container. So we need to add <em>position: relative</em> to the . <em>container</em> class and then position the first circle.</p><pre>.container {<br>  height: 15px;<br>  width: 105px;<br>  display: flex;<br>  /* added line*/<br>  position: relative;<br>}</pre><p>To select the first circle, we’re gonna use a <em>pseudo selector</em></p><pre>.container .circle:first-child {<br>  position: absolute;<br>  top: 0;<br>  left: 0;<br>}</pre><p>We have now successfully positioned the first circle. We now need to write keyframe animation to animate it. Let’s call the animation grow.</p><pre>@keyframes grow {<br>  from {<br>    transform: scale(0, 0);<br>    opacity: 0;<br>  }<br>  to {<br>    transform: scale(1, 1);<br>    opacity: 1;<br>  }<br>}</pre><p>This time, we’re animating two properties, we are increasing opacity and we are scaling the circle. Let’s apply this to the first circle</p><pre>.container .circle:first-child {<br>  position: absolute;<br>  top: 0;<br>  left: 0;<br>  /* added line */<br>  animation: grow 500ms linear 0ms infinite;<br>}</pre><p>LOOK AT THAT! We’re almost there.</p><p>We need one more circle. Add that to the html inside <em>.container</em> class</p><pre>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>  &lt;!-- added line --&gt;<br>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;</pre><p>We gotta make this circle stay at the end of the <em>.container</em> class. Yes! you guessed it! We need to add <em>position: absolute</em> to the last circle. Again we’ll be using <em>pseudo selector</em>.</p><pre>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;<br>  &lt;!-- added line --&gt;<br>  &lt;span class=&quot;circle&quot;&gt;&lt;/span&gt;</pre><p>ON TO THE LAST STEP! We need to shrink it and decrease the opacity. Rather than writing a keyframe for this, we’re gonna use the existing <em>grow</em> keyframe but we’ll reverse it.</p><pre>.container .circle:last-child {<br>  position: absolute;<br>  top: 0;<br>  right: 0;<br>  /* added line */<br>  animation: grow 500ms linear 0s infinite reverse;<br>}</pre><p>To do that, all we need to do is add the direction the animation property. It’s set to forwards by default. We are gonna set it to reverse.</p><p>VOILA! We did it! We have successfully coded the dope loader. Ain’t that illusion of continuity amusing?! Thank you for reading! Thank you for your time and patience. I hope this helped. Happy Coding and have a great day!</p><p><em>Originally published at </em><a href="https://sudeepgumaste.hashnode.dev/lets-code-a-dope-loader-with-css"><em>https://sudeepgumaste.hashnode.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2d48e31050d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/lets-code-a-dope-loader-with-css-c2d48e31050d">Let’s Code a Dope Animated Loader With CSS</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>