<?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 Jatin Parate on Medium]]></title>
        <description><![CDATA[Stories by Jatin Parate on Medium]]></description>
        <link>https://medium.com/@jatin4228?source=rss-c09322cd3d66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0WyrX6PzxbBBqIT-.jpg</url>
            <title>Stories by Jatin Parate on Medium</title>
            <link>https://medium.com/@jatin4228?source=rss-c09322cd3d66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:48:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jatin4228/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[Why Most Teams End Up Regretting Not Having a Proper Component Library]]></title>
            <link>https://medium.com/@jatin4228/why-your-project-needs-a-component-library-to-scale-6e37c724767c?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e37c724767c</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 14:47:13 GMT</pubDate>
            <atom:updated>2026-03-29T15:34:00.540Z</atom:updated>
            <content:encoded><![CDATA[<p>Look, I get it. You’re heads-down shipping features, the product is gaining traction, and the last thing you want to do is pause for some “architectural purity” exercise. But then the moment comes — and it always does — where design drops a seemingly innocent request, and your codebase turns into a horror show.</p><p>I still remember one project a few years back. We had written a piece of UI — tabs ui tightly coupled to content, and just after the demo, client wanted the tabs to be changed to accordion.</p><p>What followed was two days of painful surgery. The tab logic was tangled up with the actual settings data handling in the same files. I had to rip things apart, chase down three copy-pasted versions scattered across other pages, rewrite tests that assumed the old structure, and pray I didn’t break unrelated parts of the UI. By the end, I was cursing my past self for being “practical” and just getting it done quickly.</p><p>That pain? It’s incredibly common. And it’s almost always avoidable if you treat your UI seriously from early on.</p><h3>The Copy-Paste Tax That Quietly Kills Velocity</h3><p>The tabs nightmare wasn’t even the worst part. The real slow bleed comes from duplication.</p><p>You need a similar tab-like interface for a new dashboard feature. Someone says, “Hey, there’s one on the settings page — just copy the code.” Sounds harmless. You do it, tweak a few things for your use case, ship it.</p><p>Fast-forward a few months: a bug report comes in about keyboard navigation failing in one place but not the other. Or the active state styling looks slightly off after a design tweak. Now you have two (or five) slightly different implementations drifting apart. Fixing the bug in one doesn’t help the others. Updating styles means hunting down every instance.</p><p>I’ve watched teams end up with a dozen variations of buttons, modals, and data tables. Each one built under different deadlines, by different devs, with slightly different assumptions about focus management, loading states, or accessibility. When design finally says “we need consistent border radius everywhere,” it’s a nightmare of scattered PRs and regression testing.</p><p>A shared component library flips this. One place to fix, one source of truth. Update the &lt;Tabs /&gt; once, and every usage benefits — without touching the business logic that lives in your pages.</p><h3>Atomic Design as a Useful (But Not Religious) Framework</h3><p>Brad Frost’s Atomic Design idea has been around for a while, and it’s still one of the better mental models out there for organizing UI. It treats your interface like building blocks in chemistry: atoms, molecules, organisms, etc.</p><p>In practice, it looks something like this:</p><ul><li><strong>Atoms</strong>: The indivisible stuff — Button, Input, Icon, Badge. These shouldn’t know anything about your app’s context.</li><li><strong>Molecules</strong>: Small combinations that do one job well, like SearchBar (input + icon + button) or a FormField with label, input, and error message.</li><li><strong>Organisms</strong>: Bigger, reusable chunks — DateTable, NavigationBar, or a full SettingsPanel that might compose tabs and form fields but doesn’t care what the actual settings are.</li><li>Then templates and full pages on top.</li></ul><p>The key isn’t blindly following the hierarchy in every folder. It’s enforcing some boundaries so your pages don’t reach directly into raw atoms and create tight coupling. In one codebase I worked on, we added a simple lint rule: no importing atoms directly in page-level files. Organisms only. It prevented a ton of spaghetti without feeling overly dogmatic.</p><p>Real talk: Atomic Design isn’t magic. Some teams over-apply it and end up with bloated “atom” directories or rigid structures that fight real product needs. Others ignore the layers and wonder why everything feels coupled. Use it as a guideline, not gospel. I’ve seen it work best when paired with actual usage patterns from your product, not hypothetical perfection.</p><h3>Storybook: The Tool That Actually Changed How We Built UI</h3><p>You can have the cleanest folder structure in the world, but without a way to develop and test components in isolation, it all falls apart once the app grows.</p><p>Storybook fixed this for us in ways I didn’t fully appreciate until we had it.</p><p>Instead of spinning up the whole app, logging in, navigating to the right page, and setting up state just to tweak a dropdown, you open Storybook and see every variant instantly. Empty states, loading, error, long content that overflows, keyboard focus — all there.</p><p>Here’s a messy but real example from when we extracted our tabs:</p><p>We had stories for default tabs, curtain/drawer variant, disabled tabs, too many tabs that scroll, and one with icons. When design later wanted subtle changes to the active indicator, we could see the impact across all cases without deploying or manual testing.</p><p>It also forces better abstraction. If you can’t easily write a story because the component depends on some global context or page-specific hook, that’s a red flag. We caught a few “almost good” components this way before they spread.</p><p>Onboarding got faster too. New devs could explore the entire UI vocabulary in one place instead of grepping through the codebase for days.</p><p>Bonus: Pair it with something like Chromatic for visual regression testing. Every PR that touches a component gets pixel-level diffs of all affected stories. No more “did this padding change break something three screens away?” surprises. It saved us more than once during rushed design updates.</p><h3>Getting Started Without Over-Engineering</h3><p>The best time to start a component library is day one. The realistic time is “before it hurts too much.”</p><p>Don’t boil the ocean. Pick one painful, frequently used piece — like a button or form field — and extract it properly. Give it variants via props, write a few stories, add basic tests, and start migrating usages.</p><p>Set up Storybook early (npx storybook@latest init still works great). Establish design tokens as CSS variables right away — no hard-coded colors or spacing. That single decision makes theming or dark mode way less painful later.</p><p>Enforce loose conventions: pages compose organisms, organisms use molecules and atoms. Document props with JSDoc so Storybook surfaces it automatically.</p><p>And for god’s sake, use semantic versioning if your library is shared across teams or in a monorepo. Tools like Changesets make it almost painless. A breaking change? Major version bump. Teams upgrade when they’re ready, not when some other squad pushes a Friday refactor.</p><h3>The Objections I Hear (and Why They’re Half-Right)</h3><p>“Isn’t this overkill for a small team?”</p><p>For a true solo prototype or throwaway MVP, yeah, maybe skip the full ceremony. But as soon as you have even two or three devs and requirements start changing (they always do), the copy-paste debt piles up faster than you expect.</p><p>“We don’t have time right now.”</p><p>Tight deadlines are exactly when bad decisions bite hardest. The hours you “save” by quick duplication get multiplied later in debugging and refactoring.</p><p>“What if changing one component breaks everything?”</p><p>This fear usually comes from past trauma — someone tweaked a shared button and layouts exploded across the app. But that’s not a reason to avoid sharing. It’s a reason to get serious about testing and review processes.</p><p>Visual diffs help a lot. So does sticking to the open/closed principle: extend with new props where possible, don’t add page-specific conditionals inside shared components. If a change <em>should</em> break usages because they relied on undocumented behavior, that’s actually useful information.</p><p>The alternative — avoiding shared components out of caution — doesn’t remove risk. It just hides it in a dozen inconsistent implementations. Debugging then becomes archaeology.</p><h3>What Actually Happens After a Year or So</h3><p>With a decent library in place:</p><ul><li>New features feel faster because common patterns are already there and battle-tested.</li><li>Design tweaks propagate without hunting files.</li><li>Bugs in core UI get fixed once.</li><li>Onboarding doesn’t involve weeks of “how do we do X here?”</li></ul><p>Without it:</p><ul><li>Every UI change risks touching multiple files.</li><li>Inconsistencies creep in.</li><li>The same dumb bugs live in multiple places.</li></ul><p>It’s not glamorous work. Extracting that first few components feels slow. Maintaining stories and fixing edge cases (accessibility, mobile overflow, reduced motion preferences) takes discipline.</p><p>But the compounding return is real. I’ve been on both sides, and the projects with intentional UI foundations scaled with way less frustration.</p><p>Start small. Extract one thing today. Write its stories. Use it in a couple places. Feel the difference when you update it once and everything just works.</p><p>Then keep going. The settings panel that forces you to rethink your whole approach will come eventually — better to be ready when it does.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e37c724767c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Zero-Trust” ESLint Config: How We Scaled Node.js Quality Across Large Teams]]></title>
            <link>https://medium.com/@jatin4228/the-zero-trust-eslint-config-how-we-scaled-node-js-quality-across-large-teams-091ad397aa7d?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/091ad397aa7d</guid>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[enterprise-architecture]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 09:54:08 GMT</pubDate>
            <atom:updated>2026-03-22T09:54:08.573Z</atom:updated>
            <content:encoded><![CDATA[<p>A few years ago, I sat through a PR review that lasted three days. It wasn’t about the business logic. It was about whether we should use map or forEach, how imports should be grouped, and why a certain variable wasn&#39;t camelCase.</p><p>As our team grew, these “style nitpicks” became a significant bottleneck. More dangerously, subtle bugs — like unhandled promises and inconsistent type usage — were slipping into production because human reviewers were too distracted by formatting to see the logic.</p><p>I realized that to scale, we didn’t need more “best practice” documents. We needed a <strong>Zero-Trust Linter</strong>.</p><p>This is the story of how we built an enterprise-grade ESLint configuration for Node.js that doesn’t just find errors — it enforces a predictable, self-documenting architecture that teaches engineers as they type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQWz0vsE1B7oDJgGrOTNlA.png" /></figure><h3>The Philosophy: Linter as a Mentor, Not a Critic</h3><p>When you’re working in a large backend ecosystem, the goal of a linter should be <strong>predictability.</strong> Whether an engineer is working on the auth service, the payment gateway, or a shared library, the code should look and behave like it was written by the same person.</p><p>I built this config around four pillars:</p><ol><li><strong>Eliminating the “Silent Fail”:</strong> Every async operation must be handled. Period.</li><li><strong>Removing Decision Fatigue:</strong> Automation should handle import sorting, class ordering, and formatting.</li><li><strong>Automated Security:</strong> Hardcoded secrets and unsafe patterns should be blocked at the IDE level.</li><li><strong>Contextual Intelligence:</strong> Test files and scripts should have different rules than production code to keep developers productive.</li></ol><h3>The Tech Stack: 2026 Edition</h3><p>We moved to <strong>ESLint 9+ (Flat Config)</strong> to gain better performance and more granular control. Here’s what’s under the hood:</p><ul><li><strong>typescript-eslint</strong>: The backbone. We use projectService for deep, type-aware analysis.</li><li><strong>sonarjs &amp; </strong><strong>unicorn</strong>: These plugins identify &quot;code smells&quot; and cognitive complexity that traditional linters miss.</li><li><strong>perfectionist</strong>: Our secret weapon against PR conflicts. It automates the organization of the entire file.</li><li><strong>no-secrets &amp; </strong><strong>security</strong>: An automated security auditor that catches entropy-based secrets (like leaked API keys).</li></ul><h3>The “Gold Standard” Configuration</h3><p>Below is the result of months of iteration across multiple high-traffic Node.js services.</p><blockquote><strong><em>View the full Enterprise ESLint Configuration here:</em></strong><em> </em><strong><em>[👉 </em></strong><a href="https://gist.github.com/jatin-parate/5517ed898fbf761718470115ff05366f">https://gist.github.com/jatin-parate/5517ed898fbf761718470115ff05366f</a><strong><em>]</em></strong></blockquote><h3>Why This Strategy Wins for Large Teams</h3><h3>1. Stopping the “Import Wars”</h3><p>When you have 50 developers, everyone has a different opinion on how to group imports. By using perfectionist, the linter makes that choice for you. On every save, the code is reordered into a <strong>deterministic state.</strong> This virtually eliminates merge conflicts caused by import reordering.</p><h3>2. Guardrails that Teach</h3><p>Instead of a senior dev explaining why a function is too complex, sonarjs/cognitive-complexity flags it in real-time. The developer receives immediate feedback while they are in the flow. The linter becomes a continuous training tool that enforces clean code patterns without a human ever having to intervene.</p><h3>3. Context-Aware Strictness</h3><p>The biggest complaint with strict linters is that they make writing tests a nightmare. Our configuration uses a testConfig block that automatically relaxes rules for .spec.ts files. We allow any and &quot;dirty&quot; data in tests because we prioritize developer speed where safety is less critical, while maintaining a &quot;Zero-Trust&quot; policy for the src folder.</p><h3>🚀 The Bottom Line</h3><p>Since implementing this, our PR review sessions have transformed. We no longer talk about formatting. We talk about <strong>architecture, performance, and business logic.</strong> By automating the “boring” parts of code quality, we’ve given our engineers their time back.</p><p><strong>Want to try it out?</strong> Run the npm install for the plugins listed in the config and drop this into your eslint.config.js. Your future self (and your team) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=091ad397aa7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Worktrees: Run Multiple AI Agents (Copilot + Claude Code) on Different Branches at Once —…]]></title>
            <link>https://medium.com/@jatin4228/git-worktrees-run-multiple-ai-agents-copilot-claude-code-on-different-branches-at-once-ba46cd8e0ae7?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba46cd8e0ae7</guid>
            <category><![CDATA[git-worktree]]></category>
            <category><![CDATA[ai-coding]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 04:00:32 GMT</pubDate>
            <atom:updated>2026-03-15T04:00:32.891Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Git Worktrees: Run Multiple AI Agents (Copilot + Claude Code) on Different Branches at Once — Complete 2026 Tutorial + Node.js Setup Script</strong></h3><p><em>Stop switching branches, stashing changes, and waiting for one AI coding agent to finish. With Git worktrees you can run </em><strong><em>Copilot in one VS Code window</em></strong><em> and </em><strong><em>Claude Code in another</em></strong><em> — each focused on a completely different task or branch — all from a single repository. Zero duplication, lightning-fast setup, and massive productivity gains.</em></p><p>If you’ve ever tried to let an AI agent refactor a big feature while a hotfix needs your immediate attention, you know the pain: git stash, branch switch, lose context, wait for npm install again, explain everything to the AI from scratch.</p><p>I was in that exact loop until I discovered Git worktrees. Now I routinely run <strong>4–5 AI agents in parallel</strong> (GitHub Copilot in some windows, Claude Code in others) on separate branches, all without touching my main workspace.</p><p>In this complete, beginner-friendly guide you’ll learn:</p><ul><li>Exactly what Git worktrees are (and why you <strong>never</strong> need the bare-repo trick)</li><li>Step-by-step creation</li><li>My battle-tested setup script that automatically installs node_modules<strong>and</strong> copies your .env files (the #1 missing piece most tutorials ignore)</li><li>How to wire it up with Copilot and Claude Code for true parallel AI development</li><li>Pro tips, edge cases, cleanup, and real productivity numbers</li></ul><p>Ready? Let’s turn your repo into an AI coding factory.</p><h3>The Old Way vs. The Worktree Way</h3><p><strong>Traditional workflow</strong></p><ol><li>Working on feature auth-redesign</li><li>Urgent bug report comes in → git stash</li><li>git checkout main → fix bug → commit → push</li><li>git checkout auth-redesign → git stash pop</li><li>AI loses all context because files changed</li><li>npm install sometimes breaks again</li></ol><p>Result: 15–30 minutes lost <strong>every</strong> context switch. AI agents get confused. You get frustrated.</p><p><strong>Git worktree workflow</strong> (what I use daily)</p><ul><li>Main workspace stays on auth-redesign with Claude Code grinding away.</li><li>One command creates ../myproject-hotfix-bug-123 with full node_modules and .env .</li><li>Open it in a second VS Code window → Copilot instantly understands the bug branch.</li><li>Both agents run <strong>simultaneously</strong> with perfect isolated context.</li></ul><p>No stashing. No reinstall hell. No context loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urje4LO-qbpUEdo2P4BRnQ.jpeg" /><figcaption>Run Copilot + Claude Code on multiple branches at once with Git worktrees. Automatic Node.js + .env setup included.</figcaption></figure><h3>What Are Git Worktrees? (Super Simple Explanation)</h3><p>Git worktrees let you check out <strong>multiple branches at the same time</strong> in <strong>separate folders</strong> while sharing the same .git folder.</p><p>Think of it as having multiple “parallel universes” of your project. Each universe has its own working directory and branch, but they all share the same commit history and objects.</p><p><strong>No bare repository required</strong> (most old tutorials push the bare-repo method — ignore them). The standard git worktree add command works perfectly on any normal clone.</p><p><strong>Space savings</strong>: A full clone is ~500 MB–2 GB. A worktree adds only a few KB + your untracked files (node_modules you’ll recreate once).</p><h3>Step-by-Step: Create Your First Worktree</h3><p>Assume you’re inside your normal repo folder:</p><pre># 1. Create a new worktree for a feature branch<br>git worktree add ../myproject-feature-auth -b feature/auth-redesign main<br><br># 2. Or attach an existing remote branch<br>git worktree add ../myproject-hotfix-456 origin/hotfix/payment-bug</pre><p>That’s it! You now have two folders:</p><ul><li>myproject/ ← your original</li><li>../myproject-feature-auth/ ← brand new checkout on feature/auth-redesign</li></ul><p>Open the new folder in VS Code:</p><pre>code ../myproject-feature-auth</pre><p>Boom — separate editor, separate Git branch, same repo.</p><h3>The Magic Script: Auto-Setup node_modules + .env Files</h3><p>This is the part <strong>every</strong> other tutorial misses. When you create a worktree, Git <strong>does not</strong> copy untracked files like node_modules or .env (they’re in .gitignore).</p><p>Here’s my ready-to-copy script. Save it as ~/bin/create-ai-worktree (make executable with chmod +x), then use it forever.</p><pre>#!/bin/bash<br># create-ai-worktree — One-command worktree + Node.js + env setup<br># Usage: create-ai-worktree feature/my-new-task [base-branch]<br>set -e<br>BRANCH_NAME=&quot;$1&quot;<br>BASE_BRANCH=&quot;${2:-main}&quot;<br>REPO_NAME=$(basename &quot;$(git rev-parse --show-toplevel)&quot;)<br>WORKTREE_PATH=&quot;../${REPO_NAME}-${BRANCH_NAME##*/}&quot;  # clean name<br>echo &quot;🚀 Creating worktree for branch: $BRANCH_NAME&quot;<br># Create the worktree<br>git worktree add -b &quot;$BRANCH_NAME&quot; &quot;$WORKTREE_PATH&quot; &quot;$BASE_BRANCH&quot;<br>cd &quot;$WORKTREE_PATH&quot;<br># === COPY ENV FILES ===<br>echo &quot;📋 Copying environment files...&quot;<br>for envfile in .env .env.local .env.development .env.example; do<br>  if [ -f &quot;../$envfile&quot; ]; then<br>    cp &quot;../$envfile&quot; &quot;./$envfile&quot; 2&gt;/dev/null || true<br>    echo &quot;   Copied $envfile&quot;<br>  fi<br>done<br># === NODE.JS SETUP ===<br>if [ -f &quot;package.json&quot; ]; then<br>  echo &quot;📦 Installing node_modules (this runs only once per worktree)...&quot;<br>  npm ci --prefer-offline  # or npm install if you prefer<br>fi<br># Optional: open in VS Code + start Claude/Copilot<br>echo &quot;✅ Worktree ready at $WORKTREE_PATH&quot;<br>code .  # opens VS Code instantly<br>echo &quot;🎯 Pro tip: Run your AI agent now — it has full context!&quot;</pre><p><strong>How to install once</strong></p><pre>mkdir -p ~/bin<br># paste script above into ~/bin/create-ai-worktree<br>chmod +x ~/bin/create-ai-worktree<br>echo &#39;export PATH=&quot;$HOME/bin:$PATH&quot;&#39; &gt;&gt; ~/.zshrc  # or .bashrc</pre><p>Now just type:</p><pre>create-ai-worktree feature/auth-redesign<br>create-ai-worktree hotfix/payment-bug</pre><p>Each one installs node_modules, copies your secrets, and opens in VS Code ready for AI. Takes ~30–90 seconds the first time (subsequent ones are faster with — prefer-offline).</p><h3>How to Run Multiple AI Agents in Parallel</h3><p>This is where the magic explodes.</p><p><strong>1. GitHub Copilot</strong></p><ul><li>Open worktree folder in VS Code</li><li>Copilot works exactly as normal but on <strong>that branch only</strong></li><li>Perfect for quick bugfixes or small refactors</li></ul><p><strong>2. Claude Code</strong> (claude.ai/code or Cursor with Claude)</p><ul><li>Open the other worktree</li><li>Tell Claude the exact task (“Rewrite the entire auth flow using NextAuth v5”)</li><li>Let it run for hours while you work elsewhere</li></ul><h3>Pro Tips &amp; Edge Cases You’ll Actually Hit</h3><p><strong>Port conflicts</strong> Add this to your .env copy step or manually:</p><p>Bash</p><pre>PORT=3001  # different port per worktree</pre><p><strong>Huge node_modules?</strong> After the first install, you can symlink heavy folders (advanced):</p><pre>ln -s ../main/node_modules node_modules</pre><p><strong>Too many worktrees?</strong></p><p>Bash</p><pre>git worktree list<br>git worktree remove ../myproject-old-task<br>git branch -d old-task</pre><p><strong>Monorepos &amp; Yarn/PNPM workspaces</strong> Works perfectly — each worktree sees the full monorepo structure.</p><p><strong>Submodules or Docker volumes</strong> Update paths in .env or docker-compose overrides per worktree.</p><p><strong>Team sharing</strong> Worktrees are local only — push your branch normally and teammates can git worktree add the same way.</p><p><strong>Cleanup automation</strong> Add this alias:</p><p>Bash</p><pre>alias wt-clean=&#39;git worktree prune &amp;&amp; git branch --merged main | xargs git branch -d&#39;</pre><h3>Real Productivity Numbers (My Experience)</h3><ul><li>Context-switch time: 25 minutes → <strong>45 seconds</strong></li><li>AI tasks completed per day: 2–3 → <strong>6–8</strong></li><li>Disk space vs 5 full clones: saved <strong>4+ GB</strong></li><li>Mental load: dramatically lower (each AI has laser focus)</li></ul><p>Teams using this pattern ship features 2–3× faster because AI agents never idle.</p><h3>Common Pitfalls &amp; How to Avoid Them</h3><ul><li><strong>“Branch already checked out” error</strong> → git worktree list and remove the old one first.</li><li><strong>node_modules missing</strong> → always run the setup script (never git checkout into a worktree).</li><li><strong>.env secrets not copied</strong> → my script handles 4 common patterns automatically.</li><li><strong>Forgetting which folder is which</strong> → use consistent naming: project-branch-name.</li></ul><h3>Start Today — Your 5-Minute Action Plan</h3><ol><li>Copy the script above</li><li>Run your first worktree: create-ai-worktree test-ai-parallel</li><li>Open two VS Code windows side-by-side</li><li>Ask Copilot one thing, Claude another</li><li>Feel the power</li></ol><p>You’ll never go back to single-branch AI coding again.</p><p><strong>Drop a comment</strong>: How many AI agents are you running right now? What’s your biggest pain point with parallel development? I reply to every one.</p><p>If this post saved you hours, clap 50 times and share with one teammate who still stashes like it’s 2015.</p><p>Happy parallel coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba46cd8e0ae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Privacy-First AI Assistant That Runs Entirely in Your Browser]]></title>
            <link>https://medium.com/@jatin4228/building-a-privacy-first-ai-assistant-that-runs-entirely-in-your-browser-4ebcad57aff2?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ebcad57aff2</guid>
            <category><![CDATA[webgpu]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 18:04:55 GMT</pubDate>
            <atom:updated>2026-03-01T18:04:55.968Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>No API keys. No server costs. No data leaving your device. Here’s how I built an AI-powered CSS customization assistant using WebGPU and WebLLM.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFgTNNpFYcy9HZFlw1KR_A.png" /></figure><h3>The Problem</h3><p>Every AI-powered feature today follows the same pattern:</p><ol><li>User types a request</li><li>Request travels to a server (OpenAI, Anthropic, etc.)</li><li>Server processes and responds</li><li>Response travels back to the user</li></ol><p>This model has three fundamental problems:</p><ul><li>Privacy concerns: Every interaction is logged somewhere</li><li>Latency: Round trips add 200–1000ms minimum</li><li>Cost: Every query costs money at scale</li></ul><p>What if your web app could run AI locally, with zero API calls, while maintaining full tool-calling capabilities?</p><h3>The Solution: In-Browser AI with WebGPU</h3><p>I built a video streaming website with an AI assistant that helps users customize the UI through natural language. The entire AI model runs in the browser using WebGPU and WebLLM.</p><h3>What It Can Do</h3><p>Users can type requests like:</p><pre>&quot;Make the site blue&quot;<br>&quot;Show more videos per row&quot;<br>&quot;Increase spacing between elements&quot;<br>&quot;Make the sidebar wider&quot;</pre><p>The AI understands the request, calls the appropriate tools, and modifies CSS variables in real-time — all without leaving the user’s device.</p><h3>Architecture Overview</h3><pre>┌─────────────────────────────────────────────────────────┐<br>│                    User&#39;s Browser                       │<br>│  ┌──────────────┐    ┌──────────────┐    ┌───────────┐  │<br>│  │  React UI    │ ←→ │  Web Worker  │ ←→ │  WebLLM   │  │<br>│  │  Component   │    │  (AI Thread) │    │  + Model  │  │<br>│  └──────────────┘    └──────────────┘    └───────────┘  │<br>│         ↑                    ↑                  ↑       │<br>│         │                    │                  │       │<br>│  ┌──────────────┐    ┌──────────────┐    ┌───────────┐  │<br>│  │  CSS Vars    │ ←→ │  Tool        │    │  Hermes-2 │  │<br>│  │  (Theme)     │    │  Executor    │    │  Pro 8B   │  │<br>│  └──────────────┘    └──────────────┘    └───────────┘  │<br>└─────────────────────────────────────────────────────────┘<br>                          ↓<br>                    NO SERVER CALLS</pre><h3>Key Technologies</h3><h3>1. WebLLM (@mlc-ai/web-llm)</h3><p>WebLLM is a game-changer. It brings LLM inference to the browser using WebGPU. Unlike previous solutions that used WebAssembly (slow), WebGPU provides near-native performance by leveraging the device’s GPU.</p><pre>import * as webllm from &#39;@mlc-ai/web-llm&#39;;</pre><pre>const engine = new webllm.MLCEngine();<br>await engine.reload(&#39;Hermes-2-Pro-Llama-3-8B-q4f16_1-MLC&#39;);</pre><p>Why Hermes-2-Pro? It’s one of the few models that supports function calling (tool use) while being small enough (~5GB quantized) for browser deployment.</p><h3>2. Web Workers for Non-Blocking AI</h3><p>Running a 5GB model would freeze your UI if done on the main thread. Web Workers move the heavy lifting to a background thread:</p><pre>// ai-worker.ts<br>self.onmessage = async (event) =&gt; {<br>  const { type, payload } = event.data;<br>  <br>  if (type === &#39;CHAT&#39;) {<br>    const response = await engine.chat.completions.create({<br>      messages: payload.messages,<br>      tools: TOOLS,<br>    });<br>    self.postMessage({ type: &#39;RESPONSE&#39;, payload: response });<br>  }<br>};</pre><p>Result: Users can scroll, click, and interact while the AI processes requests.</p><h3>3. Tool Calling for Real Actions</h3><p>The AI doesn’t just chat — it does things. I defined four tools:</p><pre>const TOOLS = [<br>  {<br>    type: &#39;function&#39;,<br>    function: {<br>      name: &#39;modifyCSSVariables&#39;,<br>      description: &#39;Modify CSS variables to change site appearance&#39;,<br>      parameters: {<br>        type: &#39;object&#39;,<br>        properties: {<br>          changes: {<br>            type: &#39;array&#39;,<br>            items: {<br>              variable: { type: &#39;string&#39; },<br>              value: { type: &#39;string&#39; },<br>              reason: { type: &#39;string&#39; },<br>            },<br>          },<br>        },<br>      },<br>    },<br>  },<br>  // ... getCurrentCSSVariables, resetCSSVariables, getColorPreset<br>];</pre><p>When the AI decides to use a tool, it returns a structured response:</p><pre>{<br>  &quot;tool_calls&quot;: [{<br>    &quot;function&quot;: {<br>      &quot;name&quot;: &quot;modifyCSSVariables&quot;,<br>      &quot;arguments&quot;: &quot;{\&quot;changes\&quot;:[{\&quot;variable\&quot;:\&quot;--hue-primary\&quot;,\&quot;value\&quot;:\&quot;217\&quot;,\&quot;reason\&quot;:\&quot;Change to blue\&quot;}]}&quot;<br>    }<br>  }]<br>}</pre><p>The worker then executes the tool and sends results back.</p><h3>4. Optimized Generation Settings</h3><p>Speed matters. These settings balance quality and performance:</p><pre>const GENERATION_CONFIG = {<br>  temperature: 0.3,      // Lower = faster, more deterministic<br>  max_tokens: 300,       // Shorter responses = faster<br>  repetition_penalty: 1.1, // Prevents loops<br>};</pre><p>Impact: Response time dropped from ~8s to ~3s on M2 MacBook.</p><h3>Implementation Walkthrough</h3><h3>Step 1: Set Up WebLLM</h3><pre>npm install @mlc-ai/web-llm</pre><pre>// src/lib/ai/ai-worker.ts<br>import * as webllm from &#39;@mlc-ai/web-llm&#39;;</pre><pre>const MODEL_ID = &#39;Hermes-2-Pro-Llama-3-8B-q4f16_1-MLC&#39;;<br>let engine: webllm.MLCEngineInterface | null = null;</pre><pre>async function initialize() {<br>  engine = new webllm.MLCEngine();<br>  <br>  // Progress reporting<br>  engine.setInitProgressCallback((report) =&gt; {<br>    self.postMessage({ <br>      type: &#39;PROGRESS&#39;, <br>      payload: { progress: report.progress, text: report.text } <br>    });<br>  });</pre><pre>  await engine.reload(MODEL_ID);<br>  isInitialized = true;<br>}</pre><h3>Step 2: Define Tools</h3><pre>// Tool for modifying CSS variables<br>{<br>  type: &#39;function&#39;,<br>  function: {<br>    name: &#39;modifyCSSVariables&#39;,<br>    description: &#39;Modify CSS variables to change site appearance&#39;,<br>    parameters: {<br>      type: &#39;object&#39;,<br>      properties: {<br>        changes: {<br>          type: &#39;array&#39;,<br>          items: {<br>            type: &#39;object&#39;,<br>            properties: {<br>              variable: { <br>                type: &#39;string&#39;,<br>                description: &#39;CSS variable name&#39;<br>              },<br>              value: { <br>                type: &#39;string&#39;,<br>                description: &#39;New value&#39;<br>              },<br>              reason: { <br>                type: &#39;string&#39;,<br>                description: &#39;Why this change is made&#39;<br>              },<br>            },<br>            required: [&#39;variable&#39;, &#39;value&#39;, &#39;reason&#39;],<br>          },<br>        },<br>      },<br>      required: [&#39;changes&#39;],<br>    },<br>  },<br>}</pre><h3>Step 3: Handle Tool Execution</h3><pre>async function chat(message: string) {<br>  const messages = [<br>    { role: &#39;user&#39;, content: `${INSTRUCTIONS}\n\nRequest: ${message}` },<br>  ];</pre><pre>  const response = await engine.chat.completions.create({<br>    messages,<br>    tools: TOOLS,<br>  });</pre><pre>  const toolCalls = response.choices[0]?.message?.tool_calls;</pre><pre>  if (toolCalls) {<br>    for (const toolCall of toolCalls) {<br>      const args = JSON.parse(toolCall.function.arguments);<br>      <br>      switch (toolCall.function.name) {<br>        case &#39;modifyCSSVariables&#39;:<br>          applyCSSChanges(args.changes);<br>          break;<br>        case &#39;getColorPreset&#39;:<br>          applyColorPreset(args.colorName);<br>          break;<br>        // ... handle other tools<br>      }<br>    }<br>  }</pre><pre>  return response;<br>}</pre><h3>Step 4: React Integration</h3><pre>// src/components/AIChat.tsx<br>export default function AIChat() {<br>  const [aiStatus, setAiStatus] = useState&lt;&#39;uninitialized&#39; | &#39;initializing&#39; | &#39;ready&#39;&gt;(&#39;uninitialized&#39;);<br>  const [initProgress, setInitProgress] = useState(0);</pre><pre>  const initializeAI = async () =&gt; {<br>    setAiStatus(&#39;initializing&#39;);<br>    <br>    await aiWorker.initialize((progress, text) =&gt; {<br>      setInitProgress(progress);<br>      setInitText(text);<br>    });<br>    <br>    setAiStatus(&#39;ready&#39;);<br>  };</pre><pre>  const handleSendMessage = async (message: string) =&gt; {<br>    const response = await aiWorker.chat(message);<br>    // Display response to user<br>  };</pre><pre>  return (<br>    &lt;div&gt;<br>      {aiStatus === &#39;initializing&#39; &amp;&amp; (<br>        &lt;div&gt;Loading: {Math.round(initProgress * 100)}%&lt;/div&gt;<br>      )}<br>      {/* Chat UI */}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Performance Optimizations</h3><h3>1. Model Quantization</h3><p>Using q4f16_1 (4-bit quantization) reduces model size from ~16GB to ~5GB with minimal quality loss.</p><h3>2. Lower Temperature</h3><pre>temperature: 0.3 // vs default 0.7-1.0</pre><p>Lower temperature = more deterministic = faster sampling.</p><h3>3. Token Limits</h3><pre>max_tokens: 300      // Initial response<br>max_tokens: 150      // Follow-up (even shorter)</pre><p>Shorter responses = faster generation.</p><h3>4. Worker Persistence</h3><p>The Web Worker stays alive between sessions. No reload penalty when users reopen the chat.</p><h3>Browser Support</h3><p>Requires WebGPU, which is available in (with feature flags currently):</p><ul><li>✅ Chrome 113+</li><li>✅ Edge 113+</li><li>✅ Chrome for Android</li><li>❌ Firefox (experimental)</li><li>❌ Safari (coming soon)</li></ul><p>For unsupported browsers, gracefully degrade to a message: <em>“WebGPU not supported. Please use Chrome or Edge.”</em></p><h3>Privacy Benefits</h3><p>Traditional In-Browser AI-Requests sent to server<br>✅ All processing localData may be logged<br>✅ No data leaves deviceRequires API key<br>✅ No API key neededPer-request costs<br>✅ Zero ongoing costsRate limits<br>✅ Unlimited requests</p><h3>Challenges &amp; Solutions</h3><h3>Challenge 1: System Prompts + Tool Calling</h3><p>Hermes-2-Pro doesn’t support custom system prompts when using tools.</p><p>Solution: Embed instructions in the user message:</p><pre>const messages = [<br>  { <br>    role: &#39;user&#39;, <br>    content: `${INSTRUCTIONS}\n\nUser request: ${message}` <br>  },<br>];</pre><h3>Challenge 2: Main Thread Blocking</h3><p>Initial implementation froze the UI during model loading.</p><p>Solution: Move all AI logic to Web Worker with progress callbacks.</p><h3>Challenge 3: First Load Time</h3><p>5GB model takes time on first load even on fast network.</p><p>Solution:</p><ul><li>Show detailed progress (not just a spinner)</li><li>Cache model in IndexedDB for subsequent loads</li><li>Lazy load only when user opens chat</li></ul><h3>Performance Benchmarks</h3><p>MetricValueModel Size~5GB (quantized)<br>First Load (M2)30–45 secondsFirst Load (M2)<br>40–60 secondsSubsequent Loads<br>5–10 seconds (cached)Response Time<br>RAM Usage~6–8GB during inference</p><h3>Future Improvements</h3><ol><li>Smaller Models: Phi-3-mini (2GB) with prompt engineering for tool-like behavior</li><li>Model Caching: IndexedDB persistence across sessions</li><li>Streaming Responses: Show tokens as they’re generated</li><li>Multi-language: Support non-English requests</li><li>Offline Support: PWA + cached model for true offline AI</li></ol><h3>Conclusion</h3><p>In-browser AI isn’t just possible — it’s practical. With WebGPU and modern quantization techniques, we can run 8B parameter models with tool calling capabilities entirely client-side on high-end systems.</p><p>The benefits are clear:</p><ul><li>✅ Privacy: No data leaves the device</li><li>✅ Cost: Zero API costs</li><li>✅ No server round trips</li><li>✅ Offline: Works without internet (after initial load)</li></ul><p>The future of AI-powered features doesn’t have to mean sending every keystroke to a server. Sometimes the best cloud is no cloud.</p><p>Resources:</p><ul><li><a href="https://github.com/mlc-ai/web-llm">WebLLM GitHub</a></li><li><a href="https://www.w3.org/TR/webgpu/">WebGPU Specification</a></li><li><a href="https://huggingface.co/NousResearch/Hermes-2-Pro-Llama-3-8B">Hermes-2-Pro Model</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ebcad57aff2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable CSS with Design Tokens: How to Build a Configurable CSS Architecture That Grows With Your…]]></title>
            <link>https://medium.com/@jatin4228/scalable-css-with-design-tokens-how-to-build-a-configurable-css-architecture-that-grows-with-your-e5574b89c349?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5574b89c349</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 16:46:26 GMT</pubDate>
            <atom:updated>2026-02-28T16:46:26.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scalable CSS with Design Tokens: How to Build a Configurable CSS Architecture That Grows With Your Product</h3><p>Most CSS doesn’t fail because it’s incorrect.</p><p>It fails because it doesn’t scale.</p><p>A rebrand takes weeks.<br> Dark mode becomes a rewrite.<br> Enterprise white-labeling becomes a nightmare.<br> Spacing inconsistencies multiply.<br> Hover states drift.<br> Shadows become guesswork.</p><p><strong>The root cause?</strong></p><p>Hardcoded values and non-systematic styling.</p><p>This article will show you how to build a <strong>scalable CSS architecture using CSS variables and design tokens</strong>, where:</p><ul><li>One variable change updates the entire UI</li><li>Themes become configuration, not overrides</li><li>Density modes require zero component rewrites</li><li>Rebrands take minutes, not sprints</li></ul><p>This is not about “using CSS variables.”</p><p>This is about turning CSS into a parametric system.</p><h3>The Core Architecture of Scalable CSS</h3><figure><img alt="Infographic showing scalable CSS architecture using design tokens, structured as Primitives → Semantic Tokens → Components, demonstrating how configurable variables like brand hue, spacing unit, and font scale cascade into theming, typography, layout, and reusable UI components such as buttons, cards, and alerts." src="https://cdn-images-1.medium.com/max/1024/1*E3eSyeKKdOBnajI_1vJqyg.png" /></figure><h4>1. Primitives</h4><p>Raw configurable inputs (brand hue, base spacing, font ratio)</p><h4>2. Semantic Tokens</h4><p>Meaningful mappings (surface background, text-muted, border-color)</p><h4>3. Components</h4><p>Consume semantic tokens only — never primitives</p><p>This separation is what makes CSS scalable.</p><h3>Step 1: Define Primitives (The System Inputs)</h3><p>Start with minimal configurable variables.</p><pre>:root {<br>  /* Brand */<br>  --brand-hue: 220;<br>  --brand-saturation: 90%;<br>  --brand-lightness: 56%;<br><br>  /* Spacing base */<br>  --unit: 4px;<br><br>  /* Typography */<br>  --font-base: 1rem;<br>  --font-scale: 1.2;<br><br>  /* Radius */<br>  --radius-base: 6px;<br><br>  /* Motion */<br>  --motion-speed: 150ms;<br>}</pre><p>These are your system knobs.</p><p>Change one → everything recalculates.</p><h3>Step 2: Derive Computed Design Tokens</h3><p>Now we create mathematical relationships.</p><h4>Color System (HSL-Based Scaling)</h4><p>Using HSL allows controlled lightness shifts:</p><pre>:root {<br>  --color-primary: hsl(<br>    var(--brand-hue),<br>    var(--brand-saturation),<br>    var(--brand-lightness)<br>  );<br><br>  --color-primary-light: hsl(<br>    var(--brand-hue),<br>    var(--brand-saturation),<br>    calc(var(--brand-lightness) + 10%)<br>  );<br><br>  --color-primary-dark: hsl(<br>    var(--brand-hue),<br>    var(--brand-saturation),<br>    calc(var(--brand-lightness) - 10%)<br>  );<br>}</pre><p>Rebrand? Change --brand-hue.</p><p>Hover states, borders, badges — all update automatically.</p><h4>Spacing Scale</h4><pre>:root {<br>  --space-1: calc(var(--unit) * 1);<br>  --space-2: calc(var(--unit) * 2);<br>  --space-3: calc(var(--unit) * 4);<br>  --space-4: calc(var(--unit) * 6);<br>}</pre><p>Change --unit → entire layout density shifts.</p><p>Enterprise compact mode becomes trivial.</p><h4>Fluid Typography System</h4><pre>:root {<br>  --font-sm: calc(var(--font-base) / var(--font-scale));<br>  --font-md: var(--font-base);<br>  --font-lg: calc(var(--font-base) * var(--font-scale));<br>  --font-xl: calc(var(--font-lg) * var(--font-scale));<br>}</pre><p>Change --font-scale → whole hierarchy adjusts proportionally.</p><p>No manual rebalancing.</p><h4>Radius Scaling</h4><pre>:root {<br>  --radius-sm: calc(var(--radius-base) * 0.75);<br>  --radius-md: var(--radius-base);<br>  --radius-lg: calc(var(--radius-base) * 1.5);<br>}</pre><p>Adjust brand softness in one line.</p><h4>Elevation System</h4><pre>:root {<br>  --shadow-color: 220 40% 20%;<br>  --elevation-1: 0 1px 2px hsl(var(--shadow-color) / 0.1);<br>  --elevation-2: 0 4px 12px hsl(var(--shadow-color) / 0.15);<br>}</pre><p>Modify one hue → entire depth language shifts.</p><h3>Step 3: Create Semantic Tokens (The Secret to True Scalability)</h3><p>Components should never use --color-primary.</p><p>They should use meaning-based tokens.</p><pre>:root {<br>  --surface-bg: white;<br>  --surface-border: rgba(0,0,0,0.08);<br>  --text-primary: #111;<br>  --text-muted: #666;<br>}</pre><p>Now components stay decoupled from branding.</p><pre>.card {<br>  background: var(--surface-bg);<br>  border: 1px solid var(--surface-border);<br>  color: var(--text-primary);<br>}</pre><h3>Dark Mode Becomes Configuration, Not Overrides</h3><pre>[data-theme=&quot;dark&quot;] {<br>  --surface-bg: #111;<br>  --surface-border: rgba(255,255,255,0.1);<br>  --text-primary: #fff;<br>  --text-muted: #aaa;<br>}</pre><p>Zero component changes.</p><p>That’s scalable CSS architecture.</p><h3>Responsive Scaling Without Media Query Explosion</h3><p>Instead of rewriting components at breakpoints:</p><pre>@media (min-width: 768px) {<br>  :root {<br>    --unit: 5px;<br>    --font-base: 1.1rem;<br>  }<br>}</pre><p>Spacing, typography, layout, and rhythm scale together.</p><p>One change → systemic shift.</p><h3>Density Modes for Enterprise Applications</h3><pre>[data-density=&quot;compact&quot;] {<br>  --unit: 3px;<br>  --font-scale: 1.1;<br>}</pre><p>This supports:</p><ul><li>Admin dashboards</li><li>Data-heavy UIs</li><li>White-label enterprise systems</li></ul><p>Without component duplication.</p><h3>Why This Architecture Wins at Scale</h3><p>In large systems (100+ components, multi-brand support):</p><p>Without tokens:</p><ul><li>Rebrands are manual</li><li>Dark mode is a rewrite</li><li>Spacing drifts over time</li><li>CSS grows uncontrollably</li></ul><p>With scalable CSS:</p><ul><li>Rebrands take minutes</li><li>Theming is declarative</li><li>Density is configurable</li><li>Refactors are safe</li><li>Visual entropy decreases</li></ul><p>This is CSS as infrastructure — not decoration.</p><h3>Common Anti-Patterns That Kill Scalability</h3><ol><li>Using raw hex values in components</li><li>Using semantic tokens that reference other semantic tokens cyclically</li><li>Allowing components to override brand primitives</li><li>Mixing layout logic and design tokens</li><li>Hardcoding responsive overrides</li></ol><p>Avoid these and your CSS remains stable at scale.</p><h3>Migration Strategy for Existing Codebases</h3><p>If you’re refactoring legacy CSS:</p><ol><li>Extract repeated values into variables.</li><li>Introduce a base --unit.</li><li>Convert color system to HSL tokens.</li><li>Create semantic aliases.</li><li>Gradually refactor components to consume semantic tokens.</li></ol><p>Do not rewrite everything at once.</p><p>Tokenize progressively.</p><h3>Final Principle</h3><p>Scalable CSS is not about variables.</p><p>It is about <strong>treating your UI as a mathematical system of relationships instead of fixed values.</strong></p><p>When:</p><ul><li>Primitives are configurable,</li><li>Tokens are derived,</li><li>Components consume semantics,</li></ul><p>Your CSS stops being fragile.<br>And starts being infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5574b89c349" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding Async React (The Right Way)]]></title>
            <link>https://medium.com/@jatin4228/understanding-async-react-the-right-way-a3e523cb78e2?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3e523cb78e2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react-hooks-for-beginners]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 15:13:09 GMT</pubDate>
            <atom:updated>2025-10-18T15:18:27.418Z</atom:updated>
            <content:encoded><![CDATA[<p>After watching the latest React Conf, I got curious about the new async APIs — startTransition and useTransition.</p><p>I’d seen plenty of tweets and demos calling it “Async React,” and honestly, I had the wrong idea. I thought these hooks could defer any logic — maybe even heavy async or IO-bound computations.</p><p>Turns out, that’s not what Async React is at all. 😅</p><h3>❌ What Async React Isn’t</h3><p>Let’s get one thing straight — React’s transition APIs don’t make your code async. All the logic inside startTransition still runs synchronously.</p><p>As the React docs say (link here 👉 <a href="https://react.dev/reference/react/useTransition#starttransition-parameters">React docs on transitions</a>)</p><p>That means:</p><ul><li>Your JavaScript won’t suddenly “run in the background.”</li><li>It won’t magically delay or defer IO or computation.</li><li>It only <strong>defers state updates</strong>, not function execution.</li></ul><p>So what’s all the fuss about?</p><h3>What Async React Actually Does</h3><p>It’s all about <strong>deferring React state updates</strong>, not logic.</p><p>In other words — it tells React, “Hey, this update isn’t urgent. Handle it when you’ve got time.”</p><p>This is <em>crucial</em> when you’re dealing with complex UIs that involve:</p><ul><li>Huge lists or grids</li><li>Heavy DOM updates</li><li>Frequent state changes triggered by user input</li></ul><p>Because even a small delay in updating the DOM can block user interaction — which breaks that silky-smooth UX we all chase.</p><h3>🎬 Example: Movie Search Page</h3><p>Imagine a movie search page where every keystroke triggers:</p><ol><li>A new API call</li><li>A state update with results</li><li>A complete DOM refresh with dozens (or hundreds) of cards</li></ol><p>Now, every small interaction — even typing a letter — becomes painfully slow. We need the search bar to stay responsive, <strong>even while React is working hard rendering the new results grid</strong>.</p><p>This is exactly where transitions shine. ✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xntr7xgcDqo5N0noRQK1vQ.png" /><figcaption>Movie search page</figcaption></figure><h3>⚙️ How Transitions Work in React</h3><p>When you wrap a state update inside startTransition, React:</p><ol><li>Marks it as <em>non-urgent</em>.</li><li>Queues it up for later.</li><li>Runs it when the event loop is free — keeping the main UI thread open for high-priority updates (like typing, clicking, etc).</li></ol><p>But there’s a catch — those deferred updates must not depend directly on async logic.</p><p>If they do, you’ll need another startTransition after the async call completes.</p><h3>🧩 Real-World Example</h3><p>Here’s how my initial Movies Grid component looked like, expecting parent to pass in movies:</p><pre>export type Props = {<br>  movies: Movie[];<br>  search: string;<br>};<br><br>export default function MoviesGrid({ movies, search }: Props) {<br>  return (<br>    &lt;Grid templateColumns=&#39;repeat(4, 1fr)&#39; gap=&#39;6&#39;&gt;<br>      {movies.map(card =&gt; (<br>        &lt;GridItem key={card.id}&gt;<br>          &lt;Card.Root height=&#39;full&#39; key={card.title}&gt;<br>            &lt;Card.Body height=&#39;full&#39;&gt;<br>              &lt;Image src={card.poster} height=&#39;full&#39; /&gt;<br>            &lt;/Card.Body&gt;<br>            &lt;Card.Footer&gt;<br>              &lt;Heading size=&#39;lg&#39;&gt;{card.title}&lt;/Heading&gt;<br>            &lt;/Card.Footer&gt;<br>          &lt;/Card.Root&gt;<br>        &lt;/GridItem&gt;<br>      ))}<br>    &lt;/Grid&gt;<br>  );<br>}</pre><p>Let’s refactor our movie search component to use transitions:</p><pre>export type Props = {<br>  search: string;<br>};<br><br>export default function MoviesGrid({ search }: Props) {<br>  const [movies, setMovies] = useState&lt;Movie[]&gt;([]);<br>  const [pending, startTransition] = useTransition();<br><br>  useEffect(() =&gt; {<br>    const newAbortController = new AbortController();<br><br>    startTransition(async () =&gt; {<br>      try {<br>        const result = await fetchMovies(search, newAbortController.signal)<br><br>        if (!newAbortController.signal.aborted) {<br>          startTransition(() =&gt; {<br>            setMovies(result);<br>          });<br>        }<br>      } catch {<br>        // Ignore the errors for now<br>      }<br>    });<br><br>    return () =&gt; {<br>      newAbortController.abort();<br>    }<br>  }, [search]);<br><br>  return (<br>    &lt;&gt;<br>      {(pending)<br>        ? &lt;Spinner size=&#39;xl&#39; /&gt;<br>        : (<br>          &lt;Grid templateColumns=&#39;repeat(4, 1fr)&#39; gap=&#39;6&#39;&gt;<br>            {movies.map(card =&gt; (<br>              &lt;GridItem key={card.id}&gt;<br>                &lt;Card.Root height=&#39;full&#39; key={card.title}&gt;<br>                  &lt;Card.Body height=&#39;full&#39;&gt;<br>                    &lt;Image src={card.poster} height=&#39;full&#39; /&gt;<br>                  &lt;/Card.Body&gt;<br>                  &lt;Card.Footer&gt;<br>                    &lt;Heading size=&#39;lg&#39;&gt;{card.title}&lt;/Heading&gt;<br>                  &lt;/Card.Footer&gt;<br>                &lt;/Card.Root&gt;<br>              &lt;/GridItem&gt;<br>            ))}<br>          &lt;/Grid&gt;<br>        )<br>      }<br>    &lt;/&gt;<br>  );<br>}</pre><p>Here’s what’s happening:</p><ul><li>The fetch call is cancellable via AbortController.</li><li>Once the API responds (and hasn’t been aborted), we wrap setMovies in another transition.</li><li>This keeps the search input smooth and responsive, while the heavy movie grid updates in the background.</li></ul><h3>⚖️ Why Not Just Use react-query or useDeferredValue?</h3><p>Good question — you <em>can</em>! But there’s a key difference:</p><ul><li>react-query defers <strong>fetching logic</strong>.</li><li>useDeferredValue defers <strong>derived values</strong>.</li><li><strong>startTransition defers DOM updates.</strong></li></ul><p>It’s about what you want React to <em>delay</em>: JavaScript execution vs. React’s rendering work.</p><p>Transitions are React’s way of saying:</p><blockquote><em>“Let’s render the important stuff first. The rest can wait.”</em></blockquote><h3>Conclusion</h3><p>The movie search example is simple — but scale it up. Imagine a dashboard full of live charts, filters, sidebars, and data-heavy grids.</p><p>Without transitions, one slow update could block everything else. With transitions, React gets the breathing room to stay smooth and interactive — helping you hit that <em>sweet 60 FPS</em> target.</p><p>Async React isn’t about async code. It’s about async <em>UX</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e523cb78e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Prompt: How I Get Perfect Backend Tests from AI in One Shot]]></title>
            <link>https://medium.com/@jatin4228/the-ultimate-prompt-how-i-get-perfect-backend-tests-from-ai-in-one-shot-2eb631944280?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eb631944280</guid>
            <category><![CDATA[vitest]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 18:01:17 GMT</pubDate>
            <atom:updated>2025-10-01T18:01:17.980Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s be real: using AI to generate code can be a rollercoaster. 🎢 One minute it’s writing a brilliant function, and the next it’s producing a test suite that’s buggy, incomplete, or misses the entire point. I was tired of the endless cycle of generating, fixing, and re-generating tests for my Nest JS backend.</p><p>I realized the problem wasn’t the AI — it was me. My instructions were too vague.</p><p>So, I set out to create the ultimate prompt file: a comprehensive set of guidelines so clear and explicit that an AI could generate high-quality, production-ready tests using Vitest in a single attempt. And it worked.</p><p>This post breaks down the key components of that “master prompt.” You can adapt it to create your own instructions and stop fighting with your AI assistant.</p><h3>🏛️ The Foundation: Core Rules and Philosophy</h3><p>The first step is to eliminate guesswork. You need to tell the AI exactly what a “good test” means in the context of your project. Don’t let it make assumptions about your stack or your standards.</p><h4>Be Explicit About Your Environment</h4><p>Specify everything. The testing framework, the package manager, the Node.js version. This prevents the AI from using the wrong tools or syntax.</p><ul><li><strong>Testing Framework:</strong> Use <strong>Vitest</strong>.</li><li><strong>Package Management:</strong> Use <strong>Yarn</strong> for all commands.</li><li><strong>Runtime:</strong> Use a specific <strong>Node.js</strong> version (e.g., v24).</li></ul><h4>Define Your Testing Philosophy</h4><p>This is the most important part. You must tell the AI <em>what to test</em>, not just <em>how to write a test</em>.</p><ul><li><strong>Test Behaviour, Not Implementation:</strong> Tests must verify what the code <em>does</em>, not how it does it. This makes them less brittle to future refactoring.</li><li><strong>Enforce Independence:</strong> Each test must stand on its own. One test’s failure should never cause another to fail.</li><li><strong>Set a Clear Goal:</strong> Mandate a high code coverage target. This turns a vague request (“write tests”) into a measurable objective (“write tests that achieve 95% coverage”).</li></ul><pre># A clear instruction for the AI to verify its own work<br>yarn vitest run --coverage</pre><h3>⚙️ The Template: Test Setup and Configuration</h3><p>Consistency is crucial. Provide the AI with a non-negotiable template for setting up test suites. For NestJS, this involves using the @nestjs/testing module to create an isolated environment for each test file.</p><p>By providing a boilerplate beforeEach and afterEach structure, you enforce three critical best practices:</p><ul><li><strong>Isolated Modules:</strong> Each test suite gets its own sandboxed NestJS module.</li><li><strong>Proper Mocking:</strong> All external dependencies are replaced with mocks before any test runs.</li><li><strong>Automatic Cleanup:</strong> All mocks are reset after each test, preventing state from leaking and creating flaky results.</li></ul><p>Here’s the template I give the AI:</p><p>TypeScript</p><pre>import { Test, TestingModule } from &#39;@nestjs/testing&#39;;<br>import { getRepositoryToken } from &#39;@nestjs/typeorm&#39;;<br>import { MyService } from &#39;./my.service&#39;;<br>import { MyEntity } from &#39;./my.entity&#39;;<br>import { ExternalApiService } from &#39;../external-api/external-api.service&#39;;<br>import { vi } from &#39;vitest&#39;;<br><br>describe(&#39;MyService&#39;, () =&gt; {<br>  let service: MyService;<br>  let repository: Repository&lt;MyEntity&gt;;<br>  let externalApi: ExternalApiService;<br><br>  beforeEach(async () =&gt; {<br>    const moduleRef: TestingModule = await Test.createTestingModule({<br>      providers: [<br>        MyService,<br>        {<br>          provide: getRepositoryToken(MyEntity),<br>          useValue: {<br>            find: vi.fn(),<br>            findOne: vi.fn(),<br>            save: vi.fn(),<br>          },<br>        },<br>        {<br>          provide: ExternalApiService,<br>          useValue: {<br>            fetchData: vi.fn(),<br>          },<br>        },<br>      ],<br>    }).compile();<br><br>    service = moduleRef.get&lt;MyService&gt;(MyService);<br>      repository = moduleRef.get&lt;Repository&lt;MyEntity&gt;&gt;(getRepositoryToken(MyEntity));<br>      externalApi = moduleRef.get&lt;ExternalApiService&gt;(ExternalApiService);<br>    });<br>  <br>    afterEach(() =&gt; {<br>      vi.resetAllMocks();<br>    });<br>    // ...tests go here<br>  });</pre><h3>🧩 The Blueprint: Structure and Naming Conventions</h3><p>Clarity is king. Instruct the AI to follow the <strong>Arrange-Act-Assert (AAA)</strong> pattern for every single test case. This structure makes tests incredibly easy to read and debug.</p><p>I also provide strict naming rules. Test descriptions should describe the expected outcome of a specific scenario.</p><ul><li>✅ it(&#39;should throw a NotFoundException if the user does not exist&#39;)</li><li>✅ it(&#39;should return a user object on successful creation&#39;)</li><li>❌ it(&#39;tests the create method&#39;)</li></ul><p>This simple rule forces the tests to be behaviour-focused.</p><h3>📦 The Core Task: Mastering Mocks</h3><p>For backend testing, nothing is more important than isolating the unit of work. I give the AI a hard rule: <strong>You must not, under any circumstances, connect to a real database or make a real network call.</strong></p><h4>Database &amp; Repository Mocking</h4><p>All database interactions must be simulated. For a project using ORM Framework, this means mocking the repository layer completely. This ensures tests are lightning-fast and 100% deterministic. The AI is instructed to use getRepositoryToken() to provide mock implementations for every method the service calls.</p><h4>External Services &amp; Environment</h4><p>The same logic applies to any other external dependency. Whether it’s a third-party API, a library like dayjs, or an environment variable (process.env), it must be mocked.</p><h3>🧪 The Big Picture: Controller (E2E) Tests</h3><p>Even for higher-level tests like controller tests, the principle of isolation remains. I instruct the AI that the goal of a controller test is to verify the HTTP layer: routing, request validation, status codes, and guards.</p><p>Crucially, <strong>all underlying services and repositories must still be mocked.</strong> This isolates the controller, ensuring we are only testing its behaviour, not the entire application stack. I provide a supertest example to show exactly how this should be done.</p><p>TypeScript</p><pre>import * as request from &#39;supertest&#39;;<br>import { Test, TestingModule } from &#39;@nestjs/testing&#39;;<br>import { INestApplication, ValidationPipe } from &#39;@nestjs/common&#39;;<br>import { AppModule } from &#39;../src/app.module&#39;;<br>import { AppService } from &#39;../src/app.service&#39;;<br><br>describe(&#39;AppController (e2e)&#39;, () =&gt; {<br>  let app: INestApplication;<br>  const mockAppService = { getHello: () =&gt; &#39;Mocked Hello!&#39; };<br>  beforeEach(async () =&gt; {<br>    const moduleFixture: TestingModule = await Test.createTestingModule({<br>      imports: [AppModule],<br>    })<br>    .overrideProvider(AppService) // Crucially, we override the real service<br>    .useValue(mockAppService)<br>    .compile();<br>    app = moduleFixture.createNestApplication();<br>    app.useGlobalPipes(new ValidationPipe());<br>    await app.init();<br>  });<br>  afterEach(async () =&gt; {<br>    await app.close();<br>  });<br>  it(&#39;/ (GET)&#39;, () =&gt; {<br>    return request(app.getHttpServer())<br>      .get(&#39;/&#39;)<br>      .expect(200)<br>      .expect(&#39;Mocked Hello!&#39;);<br>  });<br>});</pre><h3>🔥 The Final Gate: A Quality Checklist</h3><p>Finally, to ensure the AI has followed all instructions, I give it a checklist to verify against its own generated code before finishing. This acts as a final set of programmatic requirements.</p><ul><li>Did you cover all public methods?</li><li>Is the coverage over 95% for statements, branches, functions, and lines?</li><li>Did you test all conditional branches (if/else, switch, etc.)?</li><li>Are all external dependencies (DB, network, etc.) properly mocked and cleaned up?</li><li>Are all test names descriptive and behaviour-focused?</li><li>Does the code have any TypeScript or linting errors?</li><li>Do all generated tests pass when run with yarn vitest run?</li></ul><h3>Conclusion</h3><p>Treating an AI like a junior developer who needs clear, explicit, and comprehensive instructions is the key to unlocking its potential. By creating a detailed “master prompt,” you move from a frustrating, iterative process to a powerful, one-shot workflow.</p><p>This approach transformed how I handle testing. Instead of writing boilerplate, I now focus on the logic, knowing that a single, well-crafted request can produce the high-quality tests my project demands.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb631944280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You’re Using AI for Coding Wrong — Try Context-Aware, Agentic IDEs]]></title>
            <link>https://medium.com/@jatin4228/youre-using-ai-for-coding-wrong-try-context-aware-agentic-ides-ba0006ed0651?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba0006ed0651</guid>
            <category><![CDATA[ai-workflow]]></category>
            <category><![CDATA[agentic-coding]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 04:48:30 GMT</pubDate>
            <atom:updated>2025-09-15T04:48:30.873Z</atom:updated>
            <content:encoded><![CDATA[<h3>You’re Using AI for Coding Wrong — Try Context-Aware, Agentic IDEs</h3><p><strong>TL;DR</strong>: Don’t just throw one-line prompts at AI and expect magic. Treat AI like a new developer on your team. Give it context, requirements, and standards. This weekend I experimented with context-aware, agentic AI IDEs — and the results were way better than I expected.</p><h3>The Wrong Way We Use AI Today</h3><p>Most of us use AI for coding like this:<br>👉 <em>“Fix this bug.”</em><br> 👉 <em>“Write me a test case.”</em><br> 👉 <em>“Build me this API endpoint.”</em></p><p>That works sometimes, but more often than not, AI either breaks something else, produces boilerplate code that doesn’t fit your project, or just fails outright.</p><p>Why? Because one-liner prompts are like giving tasks to a new hire with zero onboarding. They don’t know the project, its standards, or what you really want. No context → bad results.</p><h3>My Weekend Experiment: Agentic AI in Dev Workflows</h3><p>Instead of simple prompts, I started giving my AI structured <strong>PRDs (Product Requirement Docs)</strong> or requirement markdown files that included:</p><ul><li><strong>Context</strong>: what already exists and where</li><li><strong>Problem / Requirement</strong>: what’s expected to change or improve</li><li><strong>Instructions</strong>: coding standards, testing frameworks (e.g. <em>only use Vitest, not Jest</em>), linting rules, project folder structure, etc.</li></ul><p>Think of it like briefing a just-onboarded teammate. The difference was night and day.</p><h3>Real Wins from Context-Aware AI</h3><p>Here’s what I pulled off this weekend using agentic AI in my coding workflow:</p><ul><li>✅ <strong>Generated context-aware test cases</strong> for a React hook handling an iOS keyboard + emoji toggle focus bug. With proper context, the AI didn’t just cover that functionality but also wrote tests for unmounting, input changes, race conditions, and more — things I’d normally miss.</li><li>✅ <strong>Ran a performance audit of my NestJS API</strong>. After writing a new endpoint, I gave the AI an MD doc describing its inputs, expected outcomes, and constraints. Instead of just tweaking one file, the AI scanned the codebase, pruned unnecessary logic in shared modules, and made my endpoint faster — without breaking anything else. Previously, my “fix performance” prompts would always introduce regressions.</li></ul><h3>Beyond Code Reviews: Context Matters</h3><p>A lot of teams are already using AI in CI/CD for code reviews. That’s good, but most AI reviews today are generalized: “use better naming,” “avoid nested loops,” “add a test.”</p><p>What they <em>don’t</em> do is understand the context of a PR:</p><ul><li>What feature is this commit introducing?</li><li>Why does this change exist at a product level?</li><li>Does it align with project constraints?</li></ul><p>When you bring context into the loop, AI reviews become smarter, more relevant, and more valuable.</p><h3>Why This Matters</h3><p>Integrating context-aware AI into dev workflows does two things:</p><ol><li><strong>Improves output quality</strong> → AI produces practical, project-specific code.</li><li><strong>Improves developer habits</strong> → It forces us to write better documentation, think through workflows, and clarify requirements before coding.</li></ol><h3>The Responsibilities That Come with AI Coding</h3><p>With great power comes… you know the rest. AI coding isn’t free of responsibility. Here’s what I learned to keep in mind:</p><ol><li><strong>Consult your team</strong> before using AI on a project. Alignment matters.</li><li><strong>Check your AI tool’s privacy settings</strong>. For example, in gemini-cli I had to disable privacy.usageStatisticsEnabled (true by default). Make sure your org-level policies are respected as well.</li><li><strong>Don’t outsource your brain.</strong> Overusing AI can dull your coding skills. Use it for repetitive or heavy-lift tasks — writing basic tests, finding perf bottlenecks, or cleaning up code — but not for everything.</li></ol><h3>Closing Thoughts</h3><p>This weekend made me realize: AI coding is less about magic prompts and more about context-driven collaboration. Treat AI like a junior dev who just joined your project. Onboard it with docs, standards, and clarity — and it’ll produce work that’s surprisingly solid.</p><p>Agentic, context-aware AI IDEs aren’t the future of coding. They’re already here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba0006ed0651" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Reactive Val: A Fresh Take on State Management in React]]></title>
            <link>https://medium.com/@jatin4228/react-reactive-val-a-fresh-take-on-state-management-in-react-22948ee35a4a?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/22948ee35a4a</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Tue, 27 May 2025 08:47:31 GMT</pubDate>
            <atom:updated>2025-05-27T08:48:35.952Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing state in React applications can sometimes feel like walking a tightrope between simplicity and functionality. While solutions like Redux and Zustand have their place, there are times when we need something lighter yet powerful. Enter React Reactive Val ⚡, a lightweight state management library that brings reactive programming to React in an elegant, type-safe way.</p><h3>What is React Reactive Val? 🤔</h3><p>React Reactive Val is a minimalist state management library that provides a refreshing approach to handling reactive values in React applications. It combines the simplicity of React’s useState with the power of reactive programming, all while maintaining excellent TypeScript support and minimal bundle size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sm09doi4R1vbz-poO4YRg.png" /></figure><h3>Key Features That Make It Stand Out ✨</h3><ol><li>🛡️ <strong>Type-Safe by Design</strong>: Built with TypeScript from the ground up, offering excellent type inference and compile-time safety.</li><li>🪶 <strong>Lightweight</strong>: Zero dependencies and a tiny footprint make it perfect for projects where bundle size matters.</li><li>⚡ <strong>Performance-Focused</strong>: Built on React’s useSyncExternalStore for optimal performance.</li><li>🔄 <strong>Flexible Usage Patterns</strong>: Supports both component-local and shared state management.</li><li>📦 <strong>Modern Build System</strong>: Offers multiple format support (ESM, CommonJS, UMD) for maximum compatibility.</li></ol><h3>Getting Started 🎯</h3><p>Installation is straightforward with your preferred package manager:</p><pre>npm install react-reactive-val<br><br>Or<br><br>yarn add react-reactive-val<br><br>Or<br><br>pnpm add react-reactive-val</pre><h3>Two Ways to Use React Reactive Val 🛠️</h3><h3>1. Component-Local State with useReactiveValue 🏠</h3><p>The `useReactiveValue` hook provides a simple way to manage state within a component:</p><pre>import useReactiveValue from ‘react-reactive-val’;<br><br>function Counter() { const count = useReactiveValue(0);<br>  return (<br>    &lt;div&gt;<br>      Count: {count()}<br>      &lt;button onClick={() =&gt; count(prev =&gt; prev + 1)}&gt;<br>        Increment<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>2. Shared State with reallyReactiveVal 🌐</h3><p>For state that needs to be shared across components, use `reallyReactiveVal`:</p><pre>import { reallyReactiveVal } from ‘react-reactive-val’;<br><br>// Create a shared reactive value<br>const sharedCounter = reallyReactiveVal(0)<br><br>function CounterDisplay() {<br>  return &lt;&gt;Count: {sharedCounter()}&lt;/&gt;;<br>}<br><br>function CounterButtons() {<br>  return (<br>    &lt;button onClick={() =&gt; sharedCounter(prev =&gt; prev + 1)}&gt;+ &lt;button onClick={() =&gt; sharedCounter(prev =&gt; prev - 1)}&gt;-<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3NtUuyV7on2fNoe4cDqzA.png" /></figure><h3>Why Choose React Reactive Val? 🤩</h3><h3>1. Simplicity First 💫</h3><p>Unlike other state management solutions that require complex setup and boilerplate, React Reactive Val provides a straightforward API that feels natural to React developers. The learning curve is minimal, making it an excellent choice for both small and large projects.</p><h3>2. TypeScript Excellence 💪</h3><p>The library’s TypeScript support isn’t just an afterthought — it’s built into its core. You get full type inference out of the box:</p><pre>// Types are inferred automatically<br>const count = useReactiveValue(0); // type: number<br><br>// Or explicitly specify types<br>interface User {<br>  name: string;<br>  age: number;<br>}<br><br>const user = useReactiveValue&lt;User | null&gt;(null);</pre><h3>3. Performance 🏃‍♂️</h3><p>Built on React’s `useSyncExternalStore`, the library ensures optimal performance by leveraging React’s built-in mechanisms for state synchronization. This means you get efficient updates without unnecessary re-renders.</p><h3>4. Flexible State Updates 🔄</h3><p>The API provides a familiar yet powerful way to update state:</p><ul><li>📖 Read current value: `const value = count()`</li><li>✍️ Set new value: `count(5)`</li><li>🔄 Update based on previous value: `count(prev =&gt; prev + 1)`</li></ul><h3>Real-World Example 🌟</h3><p>Here’s a practical example showing how React Reactive Val can be used in a real application:</p><pre>import React from ‘react’;<br>import useReactiveValue, { reallyReactiveVal } from ‘react-reactive-val’;<br><br>// Shared state for theme<br><br>const themeMode = reallyReactiveVal&lt;’light’ | ‘dark’&gt;(‘light’);<br><br>function ThemeToggle() {<br>  return (<br>    &lt;button onClick={() =&gt; themeMode(current =&gt; current === ‘light’ ? ‘dark’ : &#39;light&#39;)}&gt;<br>      Toggle Theme<br>    &lt;/button&gt;<br>  );<br>}<br><br>function UserProfile() {<br>  return (<br>    &lt;div className={`profile-${themeMode()}`}&gt;<br>    Current theme: {themeMode()}<br>  );<br>}</pre><h3>When to Use React Reactive Val</h3><p>React Reactive Val is particularly well-suited for:</p><ol><li><strong>Small to Medium-sized Applications</strong>: Where Redux might be overkill</li><li><strong>Performance-Critical Components</strong>: When you need fine-grained control over updates</li><li><strong>TypeScript Projects</strong>: Where type safety is a priority</li><li><strong>Micro-frontends</strong>: Where bundle size matters</li><li><strong>Prototypes and MVPs</strong>: When you need to move fast without sacrificing scalability</li></ol><h3>Conclusion</h3><p>React Reactive Val offers a refreshing middle ground between React’s built-in state management and more complex solutions like Redux or MobX. Its combination of simplicity, type safety, and performance makes it an excellent choice for modern React applications.</p><p>Whether you’re building a small prototype or a larger application that needs efficient state management without the complexity of larger solutions, React Reactive Val provides a powerful yet approachable solution.</p><p>The library’s focus on developer experience, combined with its solid technical foundation, makes it a valuable addition to the React ecosystem. Give it a try in your next project and experience the joy of simple, reactive state management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22948ee35a4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Priority Queue using Mongo: Optimized ]]></title>
            <link>https://medium.com/@jatin4228/priority-queue-using-mongo-optimized-b528f957b03a?source=rss-c09322cd3d66------2</link>
            <guid isPermaLink="false">https://medium.com/p/b528f957b03a</guid>
            <category><![CDATA[shopify-webhook]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[priority-queue]]></category>
            <category><![CDATA[shopify]]></category>
            <dc:creator><![CDATA[Jatin Parate]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 12:37:40 GMT</pubDate>
            <atom:updated>2024-08-04T12:37:40.590Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is the continuation of my earlier post: <a href="https://medium.com/@jatin4228/multi-dimensional-priority-queue-using-mongodb-840e7f302510">Priority Queue Using MongoDB</a>.</p><p>My previous solution offers a multi-topic type priority topic, but it has the following cons/restrictions:</p><ul><li>No content de-duplication</li><li>Possibility of processing two updates of the same resource twice (ex: two updates of the same order for a store being processed by two different instances of the app simultaneously)</li><li>Not scalable, due to large usage of transactions</li></ul><h3>Requirement:</h3><p>Here are the requirements for our queue to optimize further:</p><ol><li>Deduplication of messages while inserting into Queue??</li><li>Transactions are locking collections, If possible find a solution that doesn’t use it</li></ol><p>Here’s a visual representation of the first requirement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*6IzsrsV7NvVikk1qrKMIbQ.png" /></figure><h3>Solution</h3><p>There are two points where we can prevent this issue:<br>1. At the time of insertion<br>2. Using <strong>Upsert</strong> as an atomic operation</p><p>The key is not to use transactions for performance.</p><p>Here’s a flow diagram of what we want to achieve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*OGzST0iaS7UJjYpGKE7txQ.png" /></figure><p>The test cases would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*YrVHS9Cowe2eqHHzfBtSOQ.png" /></figure><p>The code below will ensure only the latest webhook being inserted to DB and not altering anything otherwise (and it doesn’t require Transactions 😃):</p><pre>await WebhookQueue.updateOne(<br>  {<br>    storeName,<br>    &#39;data.id&#39;: orderId,<br>    orderUpdatedAt: { $gt: new Date(data.orderUpdatedAt) },<br>  },<br>  {<br>    $setOnInsert: {<br>      ...omit(data, &#39;storeName&#39;),<br>      counter: await incAndGetStoreQueueCounter(storeName),<br>    },<br>    $set: { storeName },<br>  },<br>  { upsert: true },<br>);</pre><p>We can discard any duplicate or older webhooks at the time of reading as well:</p><pre>const map = new Map();<br><br>queueItems.forEach((item) =&gt; {<br>  const existingItem = map.get(item.data.id);<br>  if (existingItem) {<br>    if (existingItem.orderUpdatedAt &lt; item.orderUpdatedAt) {<br>      // set current item instead<br>      map.set(item.data.id, item);<br>    }<br>  } else {<br>    map.set(item.data.id, item);<br>  }<br>});<br><br>await Promise.all(<br>  queueItems.map(async (item) =&gt; {<br>    try {<br>      const existingItem = map.get(item.data.id);<br>      if (existingItem._id === item._id)<br>        await processOrderUpdateWebhook(item.storeName, item.data);<br>    } finally {<br>      await deleteWebhookQueueItem(item._id).catch();<br>    }<br>  }),<br>);</pre><h3>Conclusion:</h3><p>Atomic operations save us from Transactions, which makes systems scalable and performant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b528f957b03a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>