<?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 Ajay n Jain on Medium]]></title>
        <description><![CDATA[Stories by Ajay n Jain on Medium]]></description>
        <link>https://medium.com/@ajaynjain?source=rss-c52d77ef5b61------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*uWPC31r3Xgx6FsHRQKfMUQ.jpeg</url>
            <title>Stories by Ajay n Jain on Medium</title>
            <link>https://medium.com/@ajaynjain?source=rss-c52d77ef5b61------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:28:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajaynjain/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The AI Code Trap, Part 2: How to Actually Extract Value from AI]]></title>
            <link>https://ajaynjain.medium.com/the-ai-code-trap-part-2-how-to-actually-extract-value-from-ai-2ffa5de1cd22?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ffa5de1cd22</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 05:52:10 GMT</pubDate>
            <atom:updated>2026-04-07T05:52:10.949Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last post, I talked about the hidden costs of coding with AI — specifically how relying on it can stunt our learning and create architectural nightmares when we ask the wrong questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TGl5ycs3mdG66D1v" /><figcaption>Photo by <a href="https://unsplash.com/@debrupas?utm_source=medium&amp;utm_medium=referral">Pascal Debrunner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>But let’s be real: I still use AI every single day. Why? Because while it might struggle with deep, context-heavy architectural decisions, it is an absolute game-changer when applied to the <em>right</em> tasks. When you treat AI not as a senior architect, but as an incredibly fast junior developer sitting next to you, your productivity skyrockets.</p><p>Here is where I’ve found AI coding assistants to be genuinely invaluable:</p><h3>1. Conquering the Blank Page: Project Setup and Boilerplate</h3><p>Nothing kills the excitement of a new project quite like spending the first two days writing boilerplate code. Setting up Webpack or Vite configurations, scaffolding authentication flows, connecting to databases, and building out basic CRUD endpoints is necessary, but it is deeply tedious.</p><p>This is where AI excels. You can ask an AI to “spin up a basic Node/Express backend with Prisma, PostgreSQL, and basic JWT auth,” and you have a working foundation in seconds. It completely eliminates the friction of the “blank page,” allowing you to jump straight into writing the business logic that actually matters.</p><h3>2. The Prototyping Powerhouse: Fast Feature Iteration</h3><p>Sometimes, you don’t need the perfect solution; you just need to know if an idea is actually viable.</p><p>When you are exploring new features, AI is the ultimate prototyping tool. It allows you to rapidly iterate through multiple versions of a feature to see what looks good, what feels right, and what users actually respond to.</p><blockquote><em>You can build, test, and discard three different approaches in the time it used to take to manually code just one.</em></blockquote><p>Because the code is just a prototype, the pressure for architectural perfection is off. You use AI to find the right direction quickly, and <em>then</em> you apply your engineering expertise to build the final version cleanly.</p><h3>3. Supercharging Internal Tools</h3><p>Not every piece of code needs to handle millions of requests or scale globally. Every company has a graveyard of internal tool requests — admin dashboards, data migration scripts, internal reporting tools — that get pushed to the backlog because they aren’t “high priority.”</p><p>AI is perfect for these low-stakes environments. If a feature doesn’t require complex architectural decisions or deep system integration, AI can build it almost flawlessly.</p><ul><li>Need a quick Python script to parse a messy CSV? <strong>AI does it in seconds.</strong></li><li>Need a React table to display a specific set of user data for the customer support team? <strong>AI can build the component and the styling instantly.</strong></li></ul><p>By offloading these straightforward, isolated tasks to AI, developers are freed up to spend their mental energy on the complex, customer-facing core architecture.</p><h3>4. The Ultimate Multitasking Combo: Git Worktrees + AI</h3><p>This brings me to my absolute favorite workflow hack. If you combine AI assistants with <strong>Git worktrees</strong>, your output becomes borderline superhuman.</p><p>For those who haven’t used them, Git worktrees allow you to check out multiple branches at once in separate directories, meaning you don’t have to constantly stash changes or switch branches in your main workspace.</p><p>Remember those internal tools we just talked about? The ones constantly deprioritized due to a “bandwidth crunch”? Worktrees and AI completely eliminate that excuse.</p><p>Imagine you are working on a complex core feature in your main branch. You hit a wall, or you’re waiting for a massive test suite to run. Instead of scrolling through Slack, you can just open a secondary worktree in a different terminal window. Because you are using AI, building that deprioritized internal feature doesn’t require a massive mental context switch — it is literally just <strong>another prompt in another window</strong>.</p><p>You can have the AI scaffold out an internal feature in Worktree B while you are actively reviewing the architecture of Worktree A. It takes practically zero time, zero bandwidth, and suddenly, that endless backlog of “nice-to-have” internal tools starts rapidly shrinking.</p><h3>The Takeaway</h3><p>The secret to AI-assisted coding isn’t blindly trusting it with your entire codebase. It’s about delegation and workflow optimization. Let the AI handle the setup, the prototypes, and the internal tools. Run it in parallel using worktrees. Let it do the heavy lifting on the mundane tasks, so you can save your human brainpower for the hard stuff.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ffa5de1cd22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Cost of Coding with AI: Why “Reading” Isn’t “Learning”]]></title>
            <link>https://ajaynjain.medium.com/the-hidden-cost-of-coding-with-ai-why-reading-isnt-learning-e3aef15ce6ef?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3aef15ce6ef</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 04:38:27 GMT</pubDate>
            <atom:updated>2026-04-04T04:38:27.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bewPT6v_Sk_O3kNV" /><figcaption>Photo by <a href="https://unsplash.com/@rd421?utm_source=medium&amp;utm_medium=referral">R.D. Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You sit down to build a new feature, fire up your AI assistant, and get to work. You do everything by the book: you use plan mode to outline the architecture, switch to agent mode to execute, and boom — the feature is built.</p><p>It looks great. It might even be the best possible solution with the cleanest architecture imaginable.</p><p>But here is the uncomfortable truth: <strong>You don’t actually know that.</strong> You are simply trusting it.</p><p>Even if you avoid common AI pitfalls and generate working code, there is a fundamental drawback to AI-assisted development that we aren’t talking about enough.</p><h3>The “Math Problem” Fallacy</h3><p>Let’s say you are a diligent developer. After the AI generates the feature, you sit down, read through the entire codebase, and fully understand what the AI did.</p><p>The problem? <strong>You still won’t be able to recreate it yourself.</strong> Reading code and never actually implementing it is exactly like reading complex math problems and their solutions. Sure, in that moment, you nod along and understand perfectly how the problem was solved. But ask yourself to solve a similar problem from scratch a week later, and you’ll likely draw a blank.</p><blockquote><em>Coding, like math, requires muscle memory and the productive struggle of implementation. When AI removes the struggle, it also removes the retention.</em></blockquote><h3>The XY Problem and the Context Trap</h3><p>Beyond skill degradation, there is the issue of context. We never truly know if there’s a vital piece of the puzzle the AI simply hasn’t thought of, because AI is entirely dependent on the context <em>we</em> provide.</p><p>This brings up a massive issue: <strong>The XY Problem.</strong> AI is incredibly literal. It will expertly solve the problem you ask it to solve (Y), even if it’s the completely wrong approach to your actual root problem (X).</p><p>I recently saw a piece of code that was a glaring anti-pattern. When I asked the developer why they chose that approach, they showed me their AI session. The AI had confidently told them this was the “perfect” thing to do. And based on the highly specific (but ultimately misguided) question the developer asked, the AI was technically right — but architecturally disastrous.</p><h3>The Ultimate Shift in Responsibility</h3><p>So, where does the buck stop when the code is generated by an overconfident AI and submitted by a developer who only “read the math solution”?</p><p><strong>The Pull Request Reviewers.</strong></p><p>The biggest shift in the AI coding era isn’t how fast we can write code; it’s the crushing weight of responsibility now falling on the shoulders of PR reviewers. They are no longer just checking for typos or edge cases; they are acting as the last line of defense against confident anti-patterns, context-blind architecture, and the illusion of developer mastery.</p><p>AI is an incredible tool, but if we aren’t careful, it won’t make us better developers — it will just make us faster typists relying heavily on the reviewers downstream.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3aef15ce6ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Integrated GitHub with My App (The Secure Way)]]></title>
            <link>https://javascript.plainenglish.io/how-i-integrated-github-with-my-app-the-secure-way-c289393c4d0d?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/c289393c4d0d</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 17:45:51 GMT</pubDate>
            <atom:updated>2025-08-17T00:51:06.482Z</atom:updated>
            <content:encoded><![CDATA[<h4>Don’t store secret keys on client side</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_NXFjZa56mR8MUU5" /><figcaption>Photo by <a href="https://unsplash.com/@praveentcom?utm_source=medium&amp;utm_medium=referral">Praveen Thirumurugan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Problem</h4><p>I recently faced a problem while building an application. The app was simple: it allowed users to edit an entity. As soon as they save it, it gets stored to database.</p><p>A simple database only stores the latest version. It has no built-in way to track history, show who made what change, or let you revert to a previous state.</p><p>Now if user wants to revert it, they can’t, it’s gone forever. 💀</p><h4>Solve</h4><p>The answer, I realized, was staring me in the face: <strong>version control</strong>. Specifically, using GitHub as a single source of truth for my data’s history. It would give me an instant audit trail, a complete history of every change.</p><h4>Github Technicals</h4><p>Github provides multiple ways to connect to a repository, it could be — Personal Access Token (PAT) or Fine-Grained Tokens.</p><p><strong><em>What is PAT and why I used it</em></strong></p><p>A <strong>PAT</strong> is a simple, non-expiring token tied directly to a user account. It&#39;s like an alternative password. You can give it scopes (permissions like repo or read:user) to limit what it can do.</p><ul><li><strong>Use Case:</strong> Ideal for personal scripts, command-line tools, and quick automations. It’s the simplest way to get up and running.</li><li><strong>Why I Used It:</strong> For an internal tool on a company’s GitHub Enterprise instance, a PAT is a great choice. It was quick to set up, and I could easily grant it the specific permissions needed for one repository.<br>I chose this over Fine-Grained Tokens as Fine-Grained Tokens only provided ability to connect to repo that was in my personal org, but the repo was part of company’s org.</li></ul><h4>How to integrate: Using Octokit, the official Github API client library</h4><p>We are using Next.JS as our frontend. As Octokit is the official GitHub API client library for js and offers intuitive, named methods (like repos.createOrUpdateFileContents) that are much easier to read and use than raw HTTP requests, we used it rather than constructing manually from fetch API. Plus, it provides great type safety for those of us using TypeScript.</p><h4>The token challenge</h4><p>While I had already generated <strong>PAT, </strong>to connect to Github my first thought was simple: just make an API call from my Next.js frontend. I quickly realized that on making a direct network call from client, anyone can open up the browser’s developer tools and see the API request and the secret token is exposed 🔑. Not a great look.</p><p>To solve this, I used the proxy server that comes with Next.Js, once user clicks on save to save the entity the call goes to proxy server, once the entity is saved to DB, its also saved to Github to track the history</p><h4>Code</h4><p>We use kubernetes to store all our secret and all the secrets are taken from that environment.</p><pre>const loadEnvConfig = require(&#39;@next/env&#39;).loadEnvConfig;<br><br>const githubSecret = config.githubSecret;</pre><p>As the next server used cjs and not esm, we did lazy import of octokit to get its instance and call Github Apis</p><p><strong><em>We then used two APIs from Octokit</em></strong></p><p><strong>getContent: </strong>To check if the entity that we want to commit to Github already exists or not, if it does then get its sha</p><p><strong>createOrUpdateFileContents</strong>: Now update the file with contents passed from client side along with author and committer details along with sha of the previous commit.</p><pre>import(&#39;@octokit/rest&#39;).then(({ Octokit }) =&gt; {<br>            const octokit = new Octokit({<br>                baseUrl: &#39;&lt;base url of repo&gt;&#39;,<br>                auth: &#39;githubSecret&#39;,<br>            });<br>            let sha; // To check existing commits of the file<br>            const path = &#39;&lt;file path&gt;&#39;;<br>            const owner = &#39;&lt;repo owner&gt;&#39;;<br>            const repo = &#39;&lt;repo name&gt;&#39;;<br>            octokit.rest.repos<br>                .getContent({<br>                    owner,<br>                    repo,<br>                    ref: &#39;heads/main&#39;,<br>                    path<br>                })<br>                .then((value) =&gt; {<br>                    sha = value.data.sha || undefined;<br>                })<br>                .catch(() =&gt; {<br>                    // Error is thrown when file is new i.e. no previous commits<br>                    // No OP, handle other errors accordingly<br>                })<br>                .finally(() =&gt; {<br>                    octokit.rest.repos<br>                        .createOrUpdateFileContents({<br>                            content: &#39;&lt;content of the file&gt;&#39;,<br>                            owner,<br>                            repo,<br>                            path,<br>                            branch: &#39;main&#39;,<br>                            sha,<br>                            author: {<br>                                email: `&lt;author email&gt;`,<br>                                name: `&lt;author name&gt;`<br>                            },<br>                            committer: {<br>                                email: `&lt;committer email&gt;`,<br>                                name: `&lt;committer name&gt;`<br>                            }<br>                        })<br>                        .then(() =&gt; {<br>                            res.status(201).json();<br>                        })<br>                        .catch((e) =&gt; {<br>                            res.status(400, { error: e });<br>                        });<br>                });<br>        });</pre><h4>Wrapping It Up</h4><p>By using this server-side proxy pattern, I solved a fundamental problem with tracking history. Now all the users knows what all changed as part of entity updates, whilst keeping the credentials safe.</p><p>Give it a shot for your next project! I’d love to hear your thoughts. 🚀</p><p><em>Thanks</em></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c289393c4d0d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-i-integrated-github-with-my-app-the-secure-way-c289393c4d0d">How I Integrated GitHub with My App (The Secure Way)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React.Fragment breaks your buttons]]></title>
            <link>https://ajaynjain.medium.com/react-fragment-breaks-your-buttons-f9c8f8ce879c?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9c8f8ce879c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 11:03:10 GMT</pubDate>
            <atom:updated>2025-03-30T11:03:10.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1FgZtBo2tGgepEAS" /><figcaption>Photo by <a href="https://unsplash.com/@32steps?utm_source=medium&amp;utm_medium=referral">Merve Sehirli Nasir</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I was recently working on a React Native project and I was using Touchables to handle onPress, the code was something like this</p><pre>&lt;TouchableNativeFeedback&gt;<br>  &lt;Fragment&gt;<br>    Press Button<br>  &lt;/Fragment&gt;<br>&lt;/TouchableNativeFeedback&gt;</pre><p>Once I ran this and pressed the button, it wasn’t working!</p><p>I started debugging and checked the source code from React Native to see how its actually implemented!</p><p>Once I understood it, it made me realize it uses the same headless pattern that many other libraries use, such as React Dropzone, Tanstack table!</p><p>This is the way the code is implement to make any element into a Touchable</p><pre>    const element = React.Children.only&lt;$FlowFixMe&gt;(this.props.children);<br>    const children: Array&lt;React.Node&gt; = [element.props.children];<br><br>    const {onBlur, onFocus, ...eventHandlersWithoutBlurAndFocus} =<br>      this.state.pressability.getEventHandlers();<br><br>    return React.cloneElement(<br>      element,<br>      {<br>        ...eventHandlersWithoutBlurAndFocus,<br>      },<br>      ...children,<br>    );</pre><p>As we can see here, it gets all the event handlers and attaches it to the root child using React.cloneElement.</p><h4>And the reason React Fragment doesn’t work here is because React.Fragment only accepts key and children as prop and nothing else!</h4><p>This behaviour is not only with Touchables but other UI Constructs such as tooltips!</p><blockquote><a href="https://ajaynjain.medium.com/thinking-headless-ui-2c9903015e62">Speaking of headless, check how you can implement UI Components the Headless way</a></blockquote><p><em>Thanks</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9c8f8ce879c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Whitespace crashed my app]]></title>
            <link>https://javascript.plainenglish.io/a-whitespace-crashed-my-app-fae8ff2a2af3?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/fae8ff2a2af3</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 18:48:18 GMT</pubDate>
            <atom:updated>2025-02-24T00:56:47.767Z</atom:updated>
            <content:encoded><![CDATA[<h4>Not a clickbait</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7jQCy1mmKfKNzZX1" /><figcaption>Photo by <a href="https://unsplash.com/@emileseguin?utm_source=medium&amp;utm_medium=referral">ÉMILE SÉGUIN ✳️✳️✳️</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous company, I was working on a task to improve the site’s accessibility. This included keyboard, voice, and visual aspects of it.</p><p>One of the sub task as part of this was to have accessible browser window names (<strong>document title</strong>)!</p><p>We wanted to do something similar to what chrome web store does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*5SxoA1qjk3cqURXrKI3vAg.png" /><figcaption>Extension name followed by Page Name</figcaption></figure><p>As we can see on the window, Extension name is followed by the page name, we wanted to show asset name followed by the asset type followed by the product name, something like this</p><blockquote>Asset Name | Asset Type | Product Name</blockquote><p>This product was built using <strong>Single Page App Architecture</strong> and we wanted to update the document title on each page, we used a library called as <a href="https://www.npmjs.com/package/react-helmet"><strong>React Helmet</strong></a><strong> </strong>which helped us set the title on each client side rendered page!</p><p>Another reason we went with React Helmet was because this was already used by an internal library that we used, hence no extra bundle size!!</p><blockquote>This turned out to be a bane rather than a boon :(</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JnhPQud1A2fzzXXg" /><figcaption>Photo by <a href="https://unsplash.com/@helloimnik?utm_source=medium&amp;utm_medium=referral">Nik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It turned out that the internal library was resetting the document titles to only Product Name (which it got from the app shell) x^!*#$ !!!!</p><p>We couldn’t not set the product name as it was required prop by the shell.</p><h3>A Workaround</h3><p>To overcome this, we used <a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver"><strong>MutationObserver</strong></a>! We observed document.title and checked if it got modified! We compared with the accessible title, with the modified one, and reverted if it was just the product name.</p><p>We launched! Everything was going well! Until the big crash!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WSX4uAOUXzDa6LCf" /><figcaption>Photo by <a href="https://unsplash.com/@messrro?utm_source=medium&amp;utm_medium=referral">Mehdi MeSSrro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why did the app CRASHHHH!!!!</h3><blockquote><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace"><strong>This is because the way HTML handles whitespaces! Yes there’s a whole page about it!</strong></a></blockquote><p>To update document.title we used a mutation observer, and the callback was getting triggered again and again in an infinite loop!</p><p>This was happening because the asset name contained multiple spaces between its name, something like this ASSET<strong>&lt;space&gt;&lt;space&gt;&lt;space&gt;</strong>Name</p><p>When setting it to document.title, HTML parses it, removes all the extra spaces, trailing, leading, and anything in between and then sets to the document.title</p><p>This causes mutation observer to run again, calling the callback again and essentially going to infinite looooooooooooooooooop!</p><p>This is not just for document.title rather on the complete HTML document! All the extra spaces are removed from the content!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LsRsGxFVMXX8SPhN" /><figcaption>Photo by <a href="https://unsplash.com/@vinikhill?utm_source=medium&amp;utm_medium=referral">NIKHIL</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>How do we fix this issue</h3><p>Thankfully the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace#dom_traversal_and_whitespace">same MDN link</a>, provides us with a code snippet to remove/normalize all the whitespaces!</p><pre>/**<br> * Version of `data` that doesn&#39;t include whitespace at the beginning<br> * and end and normalizes all whitespace to a single space. (Normally<br> * `data` is a property of text nodes that gives the text of the node.)<br> *<br> * @param txt  The text node whose data should be returned<br> * @return     A string giving the contents of the text node with<br> *             whitespace collapsed.<br> */<br>function dataOf(txt) {<br>  let data = txt.textContent;<br>  data = data.replace(/[\t\n\r ]+/g, &quot; &quot;);<br>  if (data[0] === &quot; &quot;) {<br>    data = data.substring(1, data.length);<br>  }<br>  if (data[data.length - 1] === &quot; &quot;) {<br>    data = data.substring(0, data.length - 1);<br>  }<br>  return data;<br>}</pre><p>We passed the asset name through this function and later set it to document.title</p><blockquote>This is how a single whitespace</blockquote><blockquote>can cause an App Crash!</blockquote><p><em>Thanks!</em></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <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=fae8ff2a2af3" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/a-whitespace-crashed-my-app-fae8ff2a2af3">A Whitespace crashed my app</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[property?: string OR property: string | undefined]]></title>
            <link>https://ajaynjain.medium.com/property-string-or-property-string-undefined-4ce83ad25a03?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ce83ad25a03</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 11:16:52 GMT</pubDate>
            <atom:updated>2024-09-22T11:16:52.283Z</atom:updated>
            <content:encoded><![CDATA[<h4>They are not same</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*a6yyUOGv-In9Ci-xjvkSdg.png" /></figure><p>If we want to make a property take an undefined value, there are two ways we can do it in JavaScript</p><pre>property?: string</pre><p>Whenever we hover over this, we get this suggestion in VS Code, which means that value of the property could either be string | defined</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*kOIP3IeIZh7IbIXgL3flvg.png" /></figure><p>The second way</p><pre>property: string | undefined</pre><p>But what’s the difference between these two, let’s see by using it</p><pre>type ExampleA = {<br>    property?: string;<br>}<br><br>type ExampleB = {<br>    property: string | undefined;<br>}<br><br>const objA: ExampleA = {};<br><br>const objB: ExampleB = {};</pre><p>While objA is fine, objB will give out a type error saying Property ‘property’ is missing in type ‘{}’ but required in type ‘ExampleB’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhqQiUBIiP48qiUAKBgTMQ.png" /></figure><p>While value of property can be string or undefined, its not an optional field, we have to explicitly define a value of it.</p><h4><strong>When to use what</strong></h4><p>Adding ? makes a property an optional field, It is really useful when we know that without it default behaviour works flawlessly.</p><p>The second way is useful when we want users to explicitly add a value to it or an undefined value. This might be in cases where the code does something different on undefined value or maybe this property is added newly to a common function and needs to be mandatory, This way we can make the users consuming this function add this property always.</p><p><em>Thanks<br>Ajay</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ce83ad25a03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Data Structure behind React —Part 1 — createRoot()]]></title>
            <link>https://ajaynjain.medium.com/the-data-structure-behind-react-part-1-createroot-6a4a6dadef26?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a4a6dadef26</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 17:25:22 GMT</pubDate>
            <atom:updated>2024-08-22T00:36:34.946Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Data Structure behind React —Part 1 — createRoot()</h3><h4>Its Fiber</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l1FjDvU4R8IKyRjZ" /><figcaption>Photo by <a href="https://unsplash.com/@_zachreiner_?utm_source=medium&amp;utm_medium=referral">Zach Reiner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Preface</h4><p>When we start with React, below is the file that is created for each project!</p><pre>import React, { StrictMode } from &#39;react&#39;;<br>import { createRoot } from &#39;react-dom/client&#39;;<br><br>import App from &#39;./App&#39;;<br><br>const rootElement = document.getElementById(&#39;root&#39;);<br>const root = createRoot(rootElement);<br><br>root.render(<br>  &lt;StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/StrictMode&gt;<br>);</pre><p>The first 3 lines are import statements. The next line is getting the root element, then we do <strong>createRoot</strong>.</p><p>We use the value returned by createRoot and render the App. Usually all our components are rendered with App, or we might use some kind of an Router Outlet and wrap the App with Routers and other Contexts!</p><blockquote>But what does React do internally when we do createRoot and root.render? Let’s find out!</blockquote><h4>createRoot</h4><p><strong>From the docs:<br></strong><em>createRoot lets you create a root to display React components inside a browser DOM node.<br>React will create a root for the </em><em>domNode, and take over managing the DOM inside it. After you’ve created a root, you need to call </em><a href="https://react.dev/reference/react-dom/client/createRoot#root-render"><em>root.render</em></a><em> to display a React component inside of it.</em></p><blockquote><strong>TLDR: Flow Diagram</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UGZa4MppxO6SG_lykqaxA.png" /></figure><p>As we can see in the Flow Diagram, when we call createRoot(element) -&gt; It checks whether the element is a valid container not. If its is valid it sets the options then calls createContainer. <br>createContainer returns <strong>FiberRoot</strong>, then markContainerAsRoot is called, then we pass the rootContainedElement to listen to supported events.</p><p>Finally we return new <strong>ReactDOMRoot</strong>(root), using this returned value, we call root.render() to render the React Components.</p><p>While this is the overall flow of createRoot method, let’s see what each method does!</p><h4>isValidContainer</h4><p>isValidContainer takes in the element that we pass and checks whether the element is <strong>non-null</strong> and if it is of <strong>HTMLNodeType</strong>. If both are true it returns true else false.</p><h4>createContainer</h4><p>This is the main function where actual container is created i.e the <strong>Fiber Node</strong>.</p><p>Below is the createContainer signature, in this article we will focus on containerInfo and tag.</p><pre>  function createContainer(<br>      containerInfo: Container,<br>      tag: RootTag,<br>      hydrationCallbacks: null | SuspenseHydrationCallbacks,<br>      isStrictMode: boolean,<br>      // TODO: Remove `concurrentUpdatesByDefaultOverride`. It is now ignored.<br>      concurrentUpdatesByDefaultOverride: null | boolean,<br>      identifierPrefix: string,<br>      onUncaughtError: (<br>        error: mixed,<br>        errorInfo: {+componentStack?: ?string},<br>      ) =&gt; void,<br>      onCaughtError: (<br>        error: mixed,<br>        errorInfo: {<br>          +componentStack?: ?string,<br>          +errorBoundary?: ?React$Component&lt;any, any&gt;,<br>        },<br>      ) =&gt; void,<br>      onRecoverableError: (<br>        error: mixed,<br>        errorInfo: {+componentStack?: ?string},<br>      ) =&gt; void,<br>      transitionCallbacks: null | TransitionTracingCallbacks,<br>): OpaqueRoot</pre><p>containerInfo is the element that we have passed to createRoot.</p><p>What is tag though → tag is of type RootTag, RootTag can either be <strong>LegacyRoot</strong> (0) or <strong>ConcurrentRoot</strong> (1).<br><strong>ConcurrentRoot</strong> is the tag that is passed with <strong>React 18</strong> now.</p><p>Now let’s see flow diagram of createContainer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sDM6EJih_Vsm7KdjQK63w.png" /></figure><p>createContainer internally calls createFiberRoot.</p><p>createFiberRoot creates a new <strong>FiberRoot </strong>Node using <strong>container</strong> and <strong>tag</strong>.</p><p>A quick reminder :) <strong>container</strong> is the <strong>element</strong> that we passed to createRoot and <strong>tag</strong> is <strong>ConcurrentRoot. </strong>Below is the type of FiberRoot.</p><p>In upcoming parts we will we will understand what each of them entails, but for now we will only focus on following properties → <strong>containerInfo, tag, and current </strong>(<strong>BaseFiberRootProperties</strong>).</p><pre>type FiberRoot = {<br>  ...BaseFiberRootProperties,<br>  ...SuspenseCallbackOnlyFiberRootProperties,<br>  ...UpdaterTrackingOnlyFiberRootProperties,<br>  ...TransitionTracingOnlyFiberRootProperties,<br>};<br><br>type BaseFiberRootProperties = {<br>  tag: RootTag,<br><br>  containerInfo: Container,<br>  pendingChildren: any,<br>  // The currently active root fiber. This is the mutable root of the tree.<br>  current: Fiber,<br><br>  pingCache: WeakMap&lt;Wakeable, Set&lt;mixed&gt;&gt; | Map&lt;Wakeable, Set&lt;mixed&gt;&gt; | null,<br><br>  finishedWork: Fiber | null,<br>  timeoutHandle: TimeoutHandle | NoTimeout,<br>  cancelPendingCommit: null | (() =&gt; void),<br>  context: Object | null,<br>  pendingContext: Object | null,<br><br>  next: FiberRoot | null,<br><br>  callbackNode: any,<br>  callbackPriority: Lane,<br>  expirationTimes: LaneMap&lt;number&gt;,<br>  hiddenUpdates: LaneMap&lt;Array&lt;ConcurrentUpdate&gt; | null&gt;,<br><br>  pendingLanes: Lanes,<br>  suspendedLanes: Lanes,<br>  pingedLanes: Lanes,<br>  expiredLanes: Lanes,<br>  errorRecoveryDisabledLanes: Lanes,<br>  shellSuspendCounter: number,<br><br>  finishedLanes: Lanes,<br><br>  entangledLanes: Lanes,<br>  entanglements: LaneMap&lt;Lanes&gt;,<br><br>  pooledCache: Cache | null,<br>  pooledCacheLanes: Lanes,<br>  identifierPrefix: string,<br><br>  onUncaughtError: (<br>    error: mixed,<br>    errorInfo: {+componentStack?: ?string},<br>  ) =&gt; void,<br>  onCaughtError: (<br>    error: mixed,<br>    errorInfo: {<br>      +componentStack?: ?string,<br>      +errorBoundary?: ?React$Component&lt;any, any&gt;,<br>    },<br>  ) =&gt; void,<br>  onRecoverableError: (<br>    error: mixed,<br>    errorInfo: {+componentStack?: ?string},<br>  ) =&gt; void,<br><br>  formState: ReactFormState&lt;any, any&gt; | null,<br>};</pre><p>Once the root node is created, <strong>createHostRootFiber </strong>is called with tag and isStrictMode.</p><p>createHostRootFiber is the function that creates <strong>Fiber</strong> for the root container. It internally calls <strong>createFiber</strong> method with a <strong>WorkTag</strong> and a <strong>Mode</strong>.</p><p>WorkTag is different than RootTag. You might remember that we had <strong>ConcurrentRoot</strong> tag when creating the root container.</p><p>To identify the type of Fiber, we have tag property of type: WorkTag.</p><p>WorkTag can be any of the following things</p><pre>export const FunctionComponent = 0;<br>export const ClassComponent = 1;<br>export const HostRoot = 3; // Root of a host tree. Could be nested inside another node.<br>export const HostPortal = 4; // A subtree. Could be an entry point to a different renderer.<br>export const HostComponent = 5;<br>export const HostText = 6;<br>export const Fragment = 7;<br>export const Mode = 8;<br>export const ContextConsumer = 9;<br>export const ContextProvider = 10;<br>export const ForwardRef = 11;<br>export const Profiler = 12;<br>export const SuspenseComponent = 13;<br>export const MemoComponent = 14;<br>export const SimpleMemoComponent = 15;<br>export const LazyComponent = 16;<br>export const IncompleteClassComponent = 17;<br>export const DehydratedFragment = 18;<br>export const SuspenseListComponent = 19;<br>export const ScopeComponent = 21;<br>export const OffscreenComponent = 22;<br>export const LegacyHiddenComponent = 23;<br>export const CacheComponent = 24;<br>export const TracingMarkerComponent = 25;<br>export const HostHoistable = 26;<br>export const HostSingleton = 27;<br>export const IncompleteFunctionComponent = 28;<br>export const Throw = 29;</pre><p>As we creating Fiber for Host Root, the work tag here will be <strong>HostRoot</strong></p><p>Below are the properties that a <strong>Fiber</strong> contains.</p><pre>// A Fiber is work on a Component that needs to be done or was done. There can<br>// be more than one per component.<br>export type Fiber = {<br>  // Tag identifying the type of fiber.<br>  tag: WorkTag,<br><br>  // Unique identifier of this child.<br>  key: null | string,<br><br>  // The value of element.type which is used to preserve the identity during<br>  // reconciliation of this child.<br>  elementType: any,<br><br>  // The resolved function/class/ associated with this fiber.<br>  type: any,<br><br>  // The local state associated with this fiber.<br>  stateNode: any,<br><br>  return: Fiber | null,<br><br>  // Singly Linked List Tree Structure.<br>  child: Fiber | null,<br>  sibling: Fiber | null,<br>  index: number,<br><br>  ref:<br>    | null<br>    | (((handle: mixed) =&gt; void) &amp; {_stringRef: ?string, ...})<br>    | RefObject,<br><br>  refCleanup: null | (() =&gt; void),<br><br>  // Input is the data coming into process this fiber. Arguments. Props.<br>  pendingProps: any, // This type will be more specific once we overload the tag.<br>  memoizedProps: any, // The props used to create the output.<br><br>  // A queue of state updates and callbacks.<br>  updateQueue: mixed,<br><br>  // The state used to create the output<br>  memoizedState: any,<br><br>  // Dependencies (contexts, events) for this fiber, if it has any<br>  dependencies: Dependencies | null,<br><br>  mode: TypeOfMode,<br><br>  // Effect<br>  flags: Flags,<br>  subtreeFlags: Flags,<br>  deletions: Array&lt;Fiber&gt; | null,<br><br>  lanes: Lanes,<br>  childLanes: Lanes,<br><br>  alternate: Fiber | null,<br><br>  actualDuration?: number,<br><br>  actualStartTime?: number,<br><br>  selfBaseDuration?: number,<br><br>  treeBaseDuration?: number,<br><br>  _debugInfo?: ReactDebugInfo | null,<br>  _debugOwner?: ReactComponentInfo | Fiber | null,<br>  _debugStack?: string | Error | null,<br>  _debugTask?: ConsoleTask | null,<br>  _debugIsCurrentlyTiming?: boolean,<br>  _debugNeedsRemount?: boolean,<br><br>  _debugHookTypes?: Array&lt;HookType&gt; | null,<br>};</pre><blockquote><em>So what is a Fiber! Well from Github Comments, we have<br></em> A Fiber is work on a Component that needs to be done or was done. There can be more than one per component.</blockquote><p>Each Fiber node contains all the details of its Component (its state, props) and is used to manage all the state updates of its component!</p><p>In upcoming parts we will see how different properties of Fiber is used to render Component and do state updates!</p><p>Post Fiber creation, Fiber is attached to rootContainer like below</p><pre>const uninitializedFiber = createHostRootFiber(tag, isStrictMode);  <br>root.current = uninitializedFiber;<br>uninitializedFiber.stateNode = root;<br><br>const initialState: RootState = {<br>  element: initialChildren,<br>  ...otherProps<br>};<br>uninitializedFiber.memoizedState = initialState;<br><br>initializeUpdateQueue(uninitializedFiber);</pre><p>UpdateQueue of a Fiber is used to manage the state updates or side effects that are to be performed in the component.</p><p>initializeUpdateQueue is a simple method to set the update queue in the fiber node with its baseState as fiber.memoizedState</p><p>createContainer method is done now!</p><h4>markContainerAsRoot</h4><p>Now we mark the container as root. It takes in the Fiber node and the element that we passed to createRoot method.</p><pre>markContainerAsRoot(root.current, container);<br><br>// Implementation<br><br>export function markContainerAsRoot(hostRoot: Fiber, node: Container): void {<br>  node[internalContainerInstanceKey] = hostRoot;<br>}<br><br>// internalContainerInstanceKey is a random unique key generated</pre><h4><strong>listenToAllSupportedEvents</strong></h4><p>Now that we have the container ready, we pass the container to listenToAllSupportedEvents to register for all the events.</p><p>listenToAllSupportedEvents internally registers for all native events.</p><p>It goes through each native event and creates the listener using the method → <strong>createEventListenerWrapperWithPriority</strong> which is part of <strong>ReactDOMEventListener.</strong></p><p>Finally the listeners are registered in both capturing phase and bubbling phase using <strong>addEventCaptureListener</strong> and <strong>addEventBubbleListener </strong>method<strong> </strong>which are part of <strong>EventListener</strong>.</p><blockquote>Finally we return return new ReactDOMRoot(root)</blockquote><p>Using this return value we do</p><pre>root.render(<br>  &lt;StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/StrictMode&gt;<br>);</pre><p>You must be wondering, where does the render method is defined!</p><p>Well <strong>render</strong> method is part of <strong>ReactDOMRoot’s prototype</strong>.<br>It accepts children and internally calls <strong>updateContainer</strong> method.</p><blockquote><strong><em>So createRoot calls createContainer and render calls updateContainer!</em></strong></blockquote><h4>Thanks</h4><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a4a6dadef26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writer’s Block]]></title>
            <link>https://ajaynjain.medium.com/writers-block-78cdd807eec5?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/78cdd807eec5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[creativity]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[mindfulness]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 00:50:37 GMT</pubDate>
            <atom:updated>2024-07-04T00:50:37.534Z</atom:updated>
            <content:encoded><![CDATA[<h4>Not for writers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TSeYWgwySoWxhbnW" /><figcaption>Photo by Tandem X Visuals on Unsplash</figcaption></figure><p>I want to put out good articles on the things that I work on, but I always face a dilemma…</p><blockquote>Is it something 🆕, is it something that’s not easily accessible, can I bring about a new 💭 to it</blockquote><p>What I want to cover today is not writing articles rather writing code.</p><p>I’ve seen this happen multiple times where I get requirements, I do the solutioning and I start writing code.</p><p>But my brain be like -&gt; We don’t do that here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sNwo9R0E5GY8WON0" /><figcaption>Photo by Gary Bendig on Unsplash</figcaption></figure><h4>What blocks me 🚫</h4><p>Thinking of the perfect solution 🥲<br>Thinking of the nth file that will be affected while writing the first file 💃<br>Thinking this, thinking that 📟</p><h4>What helps me out ✅</h4><p>0️⃣ Starting!!!<br>🔢 Starting!!!</p><p>Starting with an import statement will help my code journey better than thinking of the nth file.</p><h4>So back to the question that I ask myself</h4><p>Is it something 🆕 -&gt; NO<br>Is it something that&#39;s not easily accessible -&gt; NO<br>Can I bring about a new 💭 to it -&gt; NO</p><h4>Why am I writing this article 😶‍🌫️</h4><p>To remind myself starting is the 🗝️ <br>I know it, I forget it, this is something that&#39;ll help me to remember it back!</p><p>From me… to me...</p><p>Regards</p><p>Ajay</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78cdd807eec5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Box Shadow]]></title>
            <link>https://ajaynjain.medium.com/box-shadow-2a47b293eff3?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a47b293eff3</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[box-shadow]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Sat, 06 Apr 2024 01:42:10 GMT</pubDate>
            <atom:updated>2024-04-06T01:42:10.611Z</atom:updated>
            <content:encoded><![CDATA[<h4>A box’s crown jewel</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOuTT1uczteTtl69YSCTVw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a47b293eff3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built a Chrome Extension with React and Vite (Without CrxJS Plugin)]]></title>
            <link>https://ajaynjain.medium.com/how-i-built-a-chrome-extension-with-react-and-vite-without-crxjs-plugin-b607194c4f5e?source=rss-c52d77ef5b61------2</link>
            <guid isPermaLink="false">https://medium.com/p/b607194c4f5e</guid>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <dc:creator><![CDATA[Ajay n Jain]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 16:48:18 GMT</pubDate>
            <atom:updated>2024-03-23T16:48:18.136Z</atom:updated>
            <content:encoded><![CDATA[<h4>And solved a standing problem with Medium and other blogs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onDHyiXasykLb_5KDk62-Q.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/11082974-11082974/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5387831">11082974</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5387831">Pixabay</a></figcaption></figure><h4>Preface</h4><p>I read a lot of technical content on Medium and other blog sites, and one common issue that I faced on all of them was that they missed “<strong>Table of Contents”</strong>. They are really helpful in case of long content or if we want to revisit a particular section.</p><p>So I built an extension to solve the same and also added an ability to bookmark particular sections.</p><p><strong>Extension Link</strong>: <a href="https://chromewebstore.google.com/detail/medium-charged/dledakbcpffcmmkiemfcllmphoedblom">https://chromewebstore.google.com/detail/medium-charged/dledakbcpffcmmkiemfcllmphoedblom</a></p><p><strong>Demo</strong>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMZC__ccqGgE%3Fstart%3D1%26feature%3Doembed%26start%3D1&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMZC__ccqGgE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMZC__ccqGgE%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/a63bf661151527e48675786ee25030ae/href">https://medium.com/media/a63bf661151527e48675786ee25030ae/href</a></iframe><p>As part of this, I learned a lot on how to build an extension using React and Vite and wanted to share the same!</p><p>Before diving into how to build an extension, let’s have a quick look on what an extension entails.</p><h4>Parts of Chrome Extension</h4><p>An extension has 3 core parts — <strong>Background</strong>, <strong>Popup</strong>, and <strong>Content Script</strong>, and this is configured into <a href="https://developer.chrome.com/docs/extensions/reference/manifest/"><strong>manifest.json</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2N6V80uKcHEZ8Z2M2VIB1g.png" /><figcaption>Chrome Extension Core Parts</figcaption></figure><p><strong>Background</strong>: It’s a service worker that can be used to call APIs.</p><p><strong>Popup: </strong>Content that is displayed on click of an extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*noxHQef2naUC4TT_MKAwWg.png" /><figcaption>Grammarly Extension — Popup</figcaption></figure><p><strong>Content Script</strong>: Anything that’s injected onto the current page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iK5lXHTKxQc3KsSLa85kMw.png" /><figcaption>Grammarly Extension — Content Script (Handshake at the right end)</figcaption></figure><p>Communication between the 3 happens using <a href="https://developer.chrome.com/docs/extensions/develop/concepts/messaging">message passing</a>. These could be either using chrome.runtime API or chrome.tabs or a long-lived connection using ports. Now let’s see how we can use modern technologies and tooling to build a Chrome Extension.</p><h4>Functionalities of the Extension</h4><p>I wanted to provide 2 core functionalities in my extension.<br> — Generate Table of Contents<br> — Ability to Bookmark certain sections</p><p>And I wanted to display them on the extension popup.</p><p>To generate the table of contents, we need to inject the script onto the current page and get all the header nodes that are present.</p><p>To provide bookmarks, we need to first check which sections are bookmarked and which are not and update them accordingly.<br>chrome.bookmarks API is available only in background.js</p><p>So to build up the complete extension, I used message passing between popup and content to get the list of header nodes and then message passing between popup and background to update the bookmarks.</p><p>Now let’s look at the technology and the tooling part I used to build up the extension.</p><h4>Building the Extension</h4><p>To build <strong>Medium Charged Extension</strong>, I made use of <strong>React</strong>, <strong>TypeScript</strong>, and <strong>Vite</strong> bundler.</p><p>Let’s look at the manifest.json and see where we would be referencing all the needed files.</p><p><strong>manifest.json</strong></p><pre>{<br>    &quot;manifest_version&quot;: 3,<br>    &quot;name&quot;: &quot;Medium Charged&quot;,<br>    &quot;description&quot;: &quot;Table of Contents to help readers on any page!&quot;,<br>    &quot;version&quot;: &quot;1.0&quot;,<br>    &quot;icons&quot;: {<br>      &quot;48&quot;: &quot;images/icon.png&quot;<br>    },<br>    &quot;action&quot;: {<br>        &quot;default_popup&quot;: &quot;popup/index.html&quot;<br>    },<br>    &quot;content_scripts&quot;:[{<br>      &quot;js&quot;: [&quot;assets/content.js&quot;],<br>      &quot;matches&quot;: [&quot;https://*/*&quot;]<br>    }],<br>    &quot;background&quot;:{<br>      &quot;service_worker&quot;: &quot;assets/background.js&quot;,<br>      &quot;type&quot;: &quot;module&quot;<br>    },<br>    &quot;web_accessible_resources&quot;: [{<br>      &quot;matches&quot;: [&quot;https://*/*&quot;],<br>      &quot;resources&quot;: [&quot;assets/*&quot;]<br>   }],<br>   &quot;permissions&quot;:[&quot;bookmarks&quot;]<br>  }</pre><p>I am using React to display the Table of Contents in the popup html file.</p><p>Content is a JavaScript file that runs on the client and has access to the document and the window object.</p><p>Background is a service worker file.</p><p>Let’s see how we can set up vite project and config files to build the project.</p><h4>Setup</h4><p>To init the project we can use Vite + React + TypeScript template.</p><p>Run this in the command line, follow the prompts, and select React and TypeScript.</p><pre>npm create vite@latest</pre><p>Now let’s look at the config files.</p><p>I have used 3 different config files for all the 3 parts as all 3 serve different purposes.</p><p><strong>Config for popup (vite.config.ts):</strong></p><pre>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br><br>// https://vitejs.dev/config/<br>export default defineConfig({<br>  plugins: [react()],<br>  build:{<br>    target:&quot;esnext&quot;,<br>    rollupOptions:{<br>      input:{<br>        popup: &quot;./popup/index.html&quot;,<br>      },<br>      output:{<br>        entryFileNames: &quot;assets/[name].js&quot;<br>      }<br>    },<br>  },<br>})</pre><p><strong>Config for content (vite-content.config.ts):</strong></p><pre>import { defineConfig } from &#39;vite&#39;<br><br>// https://vitejs.dev/config/<br>export default defineConfig({<br>  build:{<br>    emptyOutDir: false, // So that popup build files don&#39;t get deleted<br>    rollupOptions:{<br>      input:{<br>        content: &quot;./content_script/content-script.ts&quot;, // Entry Point<br>        &quot;content-main&quot;: &quot;./content_script/main.ts&quot;,<br>      },<br>      output:{<br>        entryFileNames: &quot;assets/[name].js&quot;<br>      }<br>    },<br>  },<br>})</pre><p><strong>Config for background (vite-background.config.ts):</strong></p><pre>import { defineConfig } from &#39;vite&#39;<br><br>// https://vitejs.dev/config/<br>export default defineConfig({<br>    build:{<br>        emptyOutDir: false, // So that popup and content build files don&#39;t get deleted<br>        target:&quot;node16&quot;,<br>        rollupOptions:{<br>        input:{<br>            background: &quot;./background/background.ts&quot;, // Entry Point<br>        },<br>        output:{<br>            entryFileNames: &quot;assets/[name].js&quot;<br>        }<br>        },<br>    },<br>})</pre><p>Now let’s look at the directory structure and see where the config takes inputs from and finally where the build is output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*8SaRpn338Wp3-gU_vx4EBQ.png" /><figcaption>Project directory structure</figcaption></figure><p><strong>Popup folder</strong> is a standard react application folder. <br><strong>Background and Content Script folders</strong> stand as entry points as seen in the respective configs.<br><strong>Shared folder</strong> contains utils and types that are shared by all 3.<br><strong>Public folder</strong> contains manifest.json and other resources.</p><p>To generate the build we can run <strong>npm run build </strong>which will take in all the 3 config files.</p><pre>&quot;build&quot;: &quot;tsc &amp;&amp; vite build --config vite.config.ts &amp;&amp; vite build --config vite-content.config.ts &amp;&amp; vite build --config vite-background.config.ts&quot;,</pre><p>Now let’s see how the build is generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Te5xHGd74ebF99YXDHeOgg.png" /><figcaption>Build Generated</figcaption></figure><p>We can see all the compiled scripts in assets folder, and popup/index.html serving as the main entry point to the popup react application.</p><h4>Issues faced</h4><ol><li><strong>Imports in Content Script</strong>: Unlike popup and background, <strong>content script is not a module. <br></strong>To fix this I split up the content script into two. The entry point file will import the main file which is generated as a different file. <br>The main file is considered a module when its lazily imported and in the main file we can use imports.</li></ol><pre>(async() =&gt; {<br>    // We have to provide the resource as web_accessible in manifest.json<br>    // So that its available when we request using chrome.runtime.getURL<br>    const src = chrome.runtime.getURL(&#39;assets/content-main.js&#39;);<br>    await import(src);<br>})()</pre><p>2. <strong>HMR: </strong>Each time I made any change, be it in background, content, or popup, I generated the build for an extension and uploaded in chrome extensions in developer mode.<br>Unfortunately I couldn’t solve this issue :(</p><h4>Resources</h4><ol><li><a href="https://github.com/njain9104/medium-charged-chrome-extension">Code Repository</a></li><li><a href="https://developer.chrome.com/docs/extensions/get-started">Getting started with Extension Building</a></li><li><a href="https://chromewebstore.google.com/detail/medium-charged/dledakbcpffcmmkiemfcllmphoedblom">Extension Link</a></li><li><a href="https://www.youtube.com/watch?v=MZC__ccqGgE">Extension Demo Link</a></li></ol><h4>PS</h4><p>Do let me know in case you have solved the HMR, would love to discuss and update the article.</p><p><em>Thanks</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b607194c4f5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>