<?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 Frontend Queens on Medium]]></title>
        <description><![CDATA[Stories by Frontend Queens on Medium]]></description>
        <link>https://medium.com/@frontendqueens?source=rss-ef449ac5cfbb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kC6GdOFMVD3LsofyCmqicA.png</url>
            <title>Stories by Frontend Queens on Medium</title>
            <link>https://medium.com/@frontendqueens?source=rss-ef449ac5cfbb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 17:33:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@frontendqueens/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[From Prompts to Agents: The Shift Frontend Developers Can’t Ignore in 2026]]></title>
            <link>https://medium.com/@frontendqueens/from-prompts-to-agents-the-shift-frontend-developers-cant-ignore-in-2026-d58935eef961?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d58935eef961</guid>
            <category><![CDATA[agentic-loop]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai-development]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agent-engineering]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 17:23:56 GMT</pubDate>
            <atom:updated>2026-06-30T17:25:53.782Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You’ve mastered the art of talking to AI. Now it’s time to learn how to manage it.</em></p><figure><img alt="From Prompts to Agents: The Shift Frontend Developers Can’t Ignore in 2026" src="https://cdn-images-1.medium.com/max/1024/1*Ygx9J7QyMXMZ3z-MGr6u1w.png" /><figcaption>From Propmts to Agents</figcaption></figure><p>I’ve been writing frontend code for over a decade. I’ve survived the jQuery-to-React migration, the class-components-to-hooks rewrite, and more state management debates than I care to count. And now, in 2026, I find myself doing something I never expected: thinking seriously about how to <em>architect systems around AI</em>.</p><p>Not just “how do I prompt an LLM to generate this component?” We’re past that now. Something much bigger is happening.</p><p>There’s a distinction quietly forming in our industry that I think frontend developers specifically need to pay attention to. It’s the gap between <strong>prompt engineering</strong> and <strong>agentic engineering</strong> — and while they sound like two names for the same thing, they’re actually different disciplines that produce different outcomes, require different skills, and carry very different risks.</p><p>Let’s talk about what they actually are, and why you — as a frontend developer — should care about both.</p><h3>First, Let’s Define the Terms Properly</h3><h3>Prompt Engineering</h3><p>Prompt engineering is the practice of crafting inputs to a language model in a way that reliably produces the output you want. It’s a skill, and it’s more nuanced than it looks from the outside.</p><p>A good prompt engineer knows:</p><ul><li>How to structure context so the model doesn’t lose it</li><li>When to use few-shot examples versus zero-shot</li><li>How to decompose complex requests into steps the model can reason through</li><li>How to constrain output format so you can actually parse the response</li><li>How to handle hallucinations through verification layers</li></ul><p>From a frontend perspective, prompt engineering is what you’re doing when you write the system prompt for your AI chatbot component, or when you’re iterating on the instruction set that powers your “summarize this article” feature. You craft an input, you get an output, you’re done.</p><p>The interaction model is essentially: <strong>human → prompt → model → response → human</strong>.</p><p>It’s linear. It’s relatively predictable. You control the context. The model does one job and hands control back.</p><h3>Agentic Engineering</h3><p>Agentic engineering is what happens when you give the model tools, memory, and the ability to make decisions about what to do next — across multiple steps — without a human in the loop for each one.</p><p>An agent doesn’t just respond. It <em>acts</em>. It can call APIs, read files, spawn other agents, write code and execute it, evaluate the result, and try again. The interaction model looks more like:</p><p><strong>human → goal → agent → [tool call → result → reasoning → next tool call → …] → outcome → human</strong></p><p>The model isn’t generating a single response. It’s running a <em>loop</em>. And that loop can run for minutes, call dozens of tools, branch into parallel tracks, and accumulate state that affects every subsequent decision.</p><p>This is what people mean when they talk about “agentic systems” or “multi-agent pipelines.” It’s less like asking a very smart colleague a question and more like delegating a project to a team you can’t directly observe.</p><figure><img alt="Prompt Engineering vs Agentic Engineering — side-by-side flow" src="https://cdn-images-1.medium.com/max/1024/1*sgZTKigUsAN1S2yNkiobng.png" /><figcaption>Prompt Engineering vs Agentic Engineering — side-by-side flow</figcaption></figure><h3>Why Frontend Devs Specifically Need to Think About This</h3><p>Here’s the thing: most of the discourse around agentic systems has been backend-heavy. We’re talking LangChain pipelines, Python orchestration frameworks, backend tool-call routing. But frontend developers are increasingly the ones who:</p><ol><li><strong>Build the UI that users interact with to trigger agents</strong> — which means we define what goals users can express and how they’re communicated to the system</li><li><strong>Display the output of multi-step agent runs</strong> — often streaming, often partial, often needing to represent uncertainty or intermediate state</li><li><strong>Handle errors from systems we don’t control</strong> — because agents fail in weird, non-deterministic ways that are nothing like a 404</li><li><strong>Make architectural decisions about where the AI lives</strong> — in the client, in an edge function, in a backend service, in a dedicated agent runtime</li></ol><p>And increasingly: <strong>we’re the ones building the agents themselves</strong>, using tools like Vercel AI SDK, LangGraph.js, or direct Anthropic/OpenAI APIs with tool definitions.</p><p>So let’s talk about how the skills differ.</p><h3>The Skills Gap: Prompt Engineering vs Agentic Engineering</h3><h3>Thinking in Inputs vs Thinking in Systems</h3><p>With prompt engineering, your mental model is about the <em>quality of a single exchange</em>. You’re optimizing for: given this context, does the model produce the right response?</p><p>With agentic engineering, your mental model has to expand to cover <em>system behavior over time</em>. You need to think about: what happens if step 3 fails? Does the agent retry, abort, or skip? Who decides? What state does it carry forward? What can go wrong at step 7 that was caused by a bad decision at step 2?</p><p>This is, frankly, very similar to how we think about complex async data flows in frontend applications. If you’ve ever debugged a race condition in a multi-step form with async validation, you already have the instinct. You just need to apply it to AI behavior.</p><h3>Determinism vs Probabilistic Outputs</h3><p>Frontend developers are comfortable with asynchronous, non-deterministic network calls — but we expect them to eventually return something predictable. A fetch() either succeeds with a typed response or fails with an error we can handle.</p><p>An agent returns something <em>probabilistic</em>. Two runs with the same input might produce meaningfully different outputs. This isn’t a bug; it’s a feature of how language models work. But it means your error boundaries, your retry logic, and your UX for “something went wrong” need to be fundamentally more robust than what you’d build for a REST API.</p><p>Agentic engineering means <strong>designing for variance</strong> — and that’s a new muscle for most of us.</p><h3>Prompts vs Contracts</h3><p>In prompt engineering, you write instructions. In agentic engineering, you write something closer to a contract.</p><p>When an agent has tools — functions it can call to interact with the world — the tool definitions you write are not just documentation. They’re specifications that the model reasons about to decide what action to take. A poorly named tool, an ambiguous parameter description, or an unclear return value schema can cause an agent to make genuinely bad decisions that cascade.</p><p>As someone who’s spent years caring deeply about TypeScript types, API contracts, and interface design, this clicked for me immediately: <strong>tool design in agentic systems is an API design problem</strong>. The consumer happens to be a language model, but the principles are the same. Be explicit. Be consistent. Minimize ambiguity.</p><figure><img alt="Tool design in agentic systems is an API design problem.”" src="https://cdn-images-1.medium.com/max/1024/1*bvkCwmm7Qu5lwv_Cnoy1JQ.png" /><figcaption>Tool design in agentic systems is an API design problem.</figcaption></figure><h3>Stateless vs Stateful</h3><p>A prompt is stateless. You include whatever context you need in the prompt, the model responds, done. Yes, you can maintain a conversation history, but at the end of the day, each API call is self-contained.</p><p>Agents accumulate state across steps. They might write to memory, pass results between tool calls, or maintain a scratchpad that informs later decisions. This means you now have a new class of bugs to think about: state corruption, context window overflow mid-task, conflicting information from two tool results, or an agent that confidently proceeds based on stale cached data.</p><p>This is distributed systems thinking applied to AI — and it’s non-trivial.</p><figure><img alt="The Skills Gap, at a Glance" src="https://cdn-images-1.medium.com/max/1024/1*hpwdaUUCmo1JKZ-xCOV1BA.jpeg" /><figcaption>The Skills Gap, at a Glance</figcaption></figure><h3>A Concrete Frontend Example</h3><p>Let me make this concrete with something you might actually build.</p><p><strong>Scenario:</strong> You’re building a feature where a user can ask in natural language: “Update the design tokens for our dashboard to use a softer color palette.”</p><h3>The Prompt Engineering Version</h3><p>You write a carefully crafted prompt that takes the user’s natural language input + the current design token file and asks the model to return an updated token object as JSON. You parse the output, validate the schema, and apply the changes.</p><p>This works. It’s one call, one response, relatively predictable. But: what if the token file is too large for the context window? What if the user’s request is ambiguous (“softer” could mean many things)? What if the update would break contrast ratios? The model doesn’t know, and you’d need to handle all of that in your application layer.</p><h3>The Agentic Engineering Version</h3><p>You build an agent with tools:</p><ul><li>read_token_file(path) — reads the current design tokens</li><li>calculate_contrast_ratio(fg, bg) — checks WCAG compliance</li><li>update_token_value(token, value) — applies a specific change</li><li>preview_in_storybook(tokens) — renders a preview</li></ul><p>The agent reads the tokens, proposes changes incrementally, checks contrast ratios, adjusts if something fails WCAG AA, and produces a verified, safe output — all before showing you a result.</p><p>What’s driving that decision-making isn’t magic — it’s a pattern. Most agent frameworks implement something like ReAct (Reason + Act): the model reasons about what to do next, picks a tool, observes the result, then reasons again. More complex setups use plan-and-execute, where the agent drafts a full plan upfront before taking any action. You don’t need to implement these from scratch — Vercel AI SDK, LangGraph.js, and Mastra all handle the loop — but knowing the pattern helps you debug when the agent makes a wrong turn.</p><figure><img alt="Agent loop — soften the dashboard color palette" src="https://cdn-images-1.medium.com/max/1024/1*gk7vlCRK1JD9B8djTSIHuw.png" /><figcaption>Agent loop — soften the dashboard color palette</figcaption></figure><p>Same user goal. Completely different architecture. And the agentic version can handle edge cases the prompt-only version would silently get wrong.</p><p>The trade-off? The agentic version is more complex to build, harder to debug, slower to run, and more expensive. Knowing when to use which approach is the skill.</p><h3>So Which One Should You Learn?</h3><p>Both. But in sequence.</p><p><strong>Start with prompt engineering.</strong> You can’t build good agents if you can’t write good prompts — because at the core of every agentic step is still a language model making a decision, and the quality of that decision depends on how well you’ve structured the context and instructions it reasons from.</p><p>Get comfortable with:</p><ul><li>System prompt design</li><li>Few-shot prompting for structured output</li><li>Prompt templating and parameterization</li><li>Output parsing and validation</li><li>Evaluating prompt quality systematically (not just vibes)</li></ul><p><strong>Then layer in agentic thinking.</strong> Once you understand the model’s strengths and failure modes from prompt work, you’re ready to design systems that use those capabilities across multiple steps. You’ll start to see naturally where a single prompt falls short and where a loop with tools would do better.</p><p>Think about:</p><ul><li>Tool/function definition as API design</li><li>State management across agent steps</li><li>Error handling and retry strategies in non-deterministic systems</li><li>Observability — logging what the agent did and why</li><li>Human-in-the-loop checkpoints for high-stakes decisions</li></ul><h3>The Frontend-Specific Superpower</h3><p>Here’s what I think gets under appreciated: frontend developers are actually well-positioned for agentic engineering in ways that pure backend engineers sometimes aren’t.</p><p>We think about <strong>user intent</strong> all the time. What does the user want to accomplish? What’s the goal behind the action they took? That empathy for intent maps directly onto how you design agent goals and tool interfaces.</p><p>We’re comfortable with <strong>async, streaming, partial state</strong>. We render loading skeletons, optimistic updates, and error states constantly. The UI patterns for “an agent is mid-run and I don’t know when it’ll finish” are just a more extreme version of problems we’ve already solved.</p><p>We care deeply about <strong>feedback loops</strong>. Good frontend developers obsess over response time, perceived performance, and keeping users informed. Agentic systems need exactly the same attention — if an agent runs for 20 seconds, the user needs to know what it’s doing, and why, and that it hasn’t just frozen.</p><p>And honestly? We’re used to building things that <em>feel</em> smart from the outside even when the internals are a mess. That skill is going to matter a lot as agentic UX matures.</p><h3>The Honest Caveat (With Specifics)</h3><p>Agentic systems are genuinely harder to get right than prompt-based ones. They fail in stranger ways, they’re harder to test, and when they go wrong, they can go <em>confidently</em> wrong in ways that are difficult to catch.</p><p>Here are the failure modes frontend teams specifically will run into — ones that don’t show up in the backend-focused tutorials:</p><p><strong>Context window exhaustion mid-task.</strong> If you’re running an agent client-side or in an edge function, you need to actively manage what goes into the context at each step. Agents that accumulate tool results across many steps will silently hit the context limit and start dropping earlier information — often the most important parts. Unlike a server with unlimited memory and chunking infrastructure, a client-side agent has nowhere to spill. You need explicit strategies: summarize past steps, evict stale tool results, or set hard limits on agent depth before you build, not after you debug a mysterious regression at step 12.</p><p><strong>Cost blindness in streaming UIs.</strong> A prompt-based feature has a predictable cost per request. An agent that loops is pay-per-step, and users who trigger long-running agents through your UI are burning tokens every iteration — often without knowing it. Streaming UIs make this worse: the response <em>looks</em> like it’s working beautifully while the token counter climbs. You need cost monitoring baked into the agent layer, not bolted on after launch. Set per-run budgets, track token usage per tool call, and build UI affordances that communicate to users when a task is running long (and let them cancel it).</p><p><strong>Security surface of browser-side tool access.</strong> This one genuinely keeps me up at night. When you give a server-side agent tool access, you control what it can reach. When you wire tool calls through the browser — calling APIs, reading DOM state, manipulating localStorage, submitting forms — you’re potentially exposing that tool surface to prompt injection attacks. A malicious piece of content on a page your agent reads could instruct it to exfiltrate data, make unauthorized API calls, or just behave unexpectedly in ways your test suite will never catch. Treat every data source an agent reads as untrusted input. Sandbox tool permissions aggressively. Never let an agent have broader access than the minimum required for the task. This isn’t hypothetical — it’s already happening in browser agent deployments.</p><p><strong>Observability gaps that make debugging feel like archaeology.</strong> With a regular component, you open DevTools and you can see what happened. With an agentic run, the “what happened” spans multiple model calls, tool invocations, intermediate reasoning steps, and branching paths — and if you didn’t instrument it, it’s gone. Console logs won’t save you here. You need structured logging of every agent step: what tool was called, with what arguments, what it returned, what the model decided to do next, and why. LangSmith, Langfuse, Braintrust, and similar tools exist for this — but you have to wire them in from day one. The developers who skip observability to ship faster spend three times as long debugging production incidents.</p><p>Don’t reach for an agent when a good prompt solves the problem. The complexity cost is real, and these failure modes are not theoretical.</p><p>But equally: don’t dismiss agentic approaches because they feel overwhelming. The mental models you already have as a senior frontend developer — thinking in systems, designing interfaces, managing state, handling failure gracefully — transfer more than you might think.</p><p>The tools are new. The discipline isn’t.</p><h3>Where to Start (Actually)</h3><p>If this resonated and you want to move from theory to practice, here’s the most direct path I’d recommend:</p><p><strong>Step 1: Get comfortable with tool calling through the Vercel AI SDK.</strong> The useChat hook with tool definitions is the gentlest on-ramp to agentic thinking available to frontend devs right now. Build something small and frontend-native — an agent that reads your package.json, identifies outdated dependencies, and suggests upgrade priorities. It&#39;s a single-tool, single-step agent, but you&#39;ll immediately hit the real problems: how do you define the tool clearly enough that the model uses it correctly? How do you display intermediate state in the UI? How do you handle a result the model misinterprets? All the core agentic muscles, in a controlled environment you can fully reason about.</p><p><strong>Step 2: Add a second tool and make them interact.</strong> The complexity jump from one tool to two is where agentic engineering really starts. Try extending the above: add a check_changelog(package) tool that fetches breaking changes, and watch how the model decides <em>when</em> to call which tool and in what order. This is where tool design as API design clicks — because a poorly scoped second tool will cause the model to call things in the wrong sequence or conflate responsibilities. Fix it the same way you&#39;d fix a badly designed API: clearer names, tighter contracts, explicit return shapes.</p><figure><img alt="“Where to Start — Build Up Gradually” staircase" src="https://cdn-images-1.medium.com/max/1024/1*sImA0qgSeAtBh3Qqm3oSMA.jpeg" /><figcaption>“Where to Start — Build Up Gradually” staircase</figcaption></figure><p>Once you’ve done both of those, you’ll have enough intuition to evaluate the heavier orchestration frameworks — <a href="https://docs.langchain.com/oss/javascript/langgraph/overview">LangGraph.js</a>, <a href="https://mastra.ai/">Mastra</a>, or direct multi-agent patterns via the Anthropic or OpenAI APIs — from a position of actual experience rather than documentation skimming.</p><p>Start small. Ship something broken. Fix it. That’s still how we learn.</p><h4>About the Author</h4><p><strong><em>Violina Popova</em></strong><em> is a software developer with over a decade of experience in the tech industry, specialising in building scalable cross-platform applications. She is currently a developer at ClipMyHorse.TV, the world’s leading video streaming platform for equestrian sports, where she works on delivering high-quality digital experiences to a global audience.</em></p><p><em>You can connect with </em><strong><em>Violina</em></strong><em> on </em><a href="https://www.linkedin.com/in/violipopova/"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d58935eef961" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Might Not Need a Framework for That]]></title>
            <link>https://medium.com/@frontendqueens/you-might-not-need-a-framework-for-that-299924186b78?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/299924186b78</guid>
            <category><![CDATA[wcag]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 14:43:48 GMT</pubDate>
            <atom:updated>2026-06-25T14:43:48.334Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvdhWQFKXwv1jBaue-XDHw.jpeg" /><figcaption>Do you really need a framework for every project?</figcaption></figure><p><strong>Three things I assumed needed a library until I found out the browser already did them.</strong></p><p>When I started learning frontend, my instinct for almost everything was to install something. Need a modal? There’s a package for that. Smooth scrolling? Package. Copy a bit of text to the clipboard? Surely a package.</p><p>It took me a while to realize that a lot of these instincts were out of date before I even picked them up. The advice I was learning from was written for an older browser — one that genuinely couldn’t do these things, so people filled the gaps with libraries. But the browser kept getting better, and a lot of that older advice never got updated.</p><p>So I started checking. Before installing anything, I’d ask: <em>can the browser already do this?</em> More often than I expected, the answer was yes. Here are three examples that changed how I build — and that you can drop into a project today without adding a single dependency.</p><h3>1. Modals, with the &lt;dialog&gt; element</h3><figure><img alt="Modals, with the &lt;dialog&gt; element" src="https://cdn-images-1.medium.com/max/1024/1*MY1dxyWmh_jRgPFifqYJaQ.jpeg" /><figcaption>Modals, with the &lt;dialog&gt; element</figcaption></figure><p>Building a modal from scratch is one of those things that looks easy and isn’t. You have to trap focus inside it so keyboard users don’t tab out into the page behind. You have to close it on the Escape key. You have to handle the dark backdrop. You have to announce it correctly to screen readers. Get any of these wrong and you’ve shipped something that’s broken for a real group of people.</p><p>This is exactly why I used to grab a modal library. Then I learned the browser has a native &lt;dialog&gt; element that handles all of it.</p><pre>&lt;dialog id=&quot;confirm&quot;&gt;<br>  &lt;h2&gt;Delete this item?&lt;/h2&gt;<br>  &lt;p&gt;This can&#39;t be undone.&lt;/p&gt;<br>  &lt;button id=&quot;cancel&quot;&gt;Cancel&lt;/button&gt;<br>  &lt;button id=&quot;ok&quot;&gt;Delete&lt;/button&gt;<br>&lt;/dialog&gt;<br><br>const dialog = document.querySelector(&#39;#confirm&#39;);<br><br>openBtn.addEventListener(&#39;click&#39;, () =&gt; dialog.showModal());<br>cancelBtn.addEventListener(&#39;click&#39;, () =&gt; dialog.close());</pre><p>That’s it. showModal() opens it as a real modal — focus gets trapped inside, Escape closes it, and a backdrop appears behind it automatically. You can even style that backdrop:</p><pre>dialog::backdrop {<br>  background: rgb(0 0 0 / 0.5);<br>  backdrop-filter: blur(3px);<br>}</pre><p>The part I appreciate most is the accessibility. A native &lt;button&gt; is already keyboard-friendly and screen-reader-friendly without any extra work, and &lt;dialog&gt; extends that to the whole modal. When you build your own from a &lt;div&gt;, all of that becomes your job — and it’s easy to miss a piece.</p><h3>2. Scroll-triggered animations, with Intersection Observer</h3><figure><img alt="Scroll-triggered animation with IntersectionObserver" src="https://cdn-images-1.medium.com/max/1024/1*xwjvv1eAT316UNwiFv7Q3A.png" /><figcaption>Scroll-triggered animations</figcaption></figure><p>You know that effect where elements fade in as you scroll down to them? I always thought that needed a library, because the old way of doing it was genuinely awful: listen to every scroll event, calculate each element’s position against the viewport, and try not to tank performance in the process.</p><p>The modern way is the <strong>Intersection Observer API</strong>. You tell the browser “watch these elements and let me know when they come into view,” and it does the heavy lifting efficiently in the background.</p><pre>.reveal {<br>  opacity: 0;<br>  transform: translateY(20px);<br>  transition: 0.6s ease;<br>}<br>.reveal.visible {<br>  opacity: 1;<br>  transform: none;<br>}</pre><pre>const observer = new IntersectionObserver((entries) =&gt; {<br>  entries.forEach(entry =&gt; {<br>    if (entry.isIntersecting) {<br>      entry.target.classList.add(&#39;visible&#39;);<br>      observer.unobserve(entry.target); // only animate once<br>    }<br>  });<br>}, { threshold: 0.15 }); // fire when 15% of the element is visible<br><br>document.querySelectorAll(&#39;.reveal&#39;).forEach(el =&gt; observer.observe(el));</pre><p>The same idea powers infinite scroll. Instead of watching content, you put an invisible marker element at the bottom of your list and observe <em>that</em> — when it scrolls into view, you load the next page:</p><pre>const sentinel = document.querySelector(&#39;#load-more&#39;);<br><br>const loader = new IntersectionObserver(async (entries) =&gt; {<br>  if (entries[0].isIntersecting) {<br>    const items = await fetchNextPage();<br>    renderItems(items);<br>  }<br>});<br><br>loader.observe(sentinel);</pre><p>No scroll math, no performance worries. The browser only calls your code when something actually crosses the threshold you set.</p><h3>3. Copy to clipboard, with the Clipboard API</h3><figure><img alt="The Clipboard API" src="https://cdn-images-1.medium.com/max/1024/1*DWpIopHkDnE0awv2n1K_TA.png" /><figcaption>The Clipboard API</figcaption></figure><p>This is the small one, but it’s the one I reached for a library for the most often, and it turns out you really don’t need to.</p><pre>copyBtn.addEventListener(&#39;click&#39;, async () =&gt; {<br>  try {<br>    await navigator.clipboard.writeText(code.textContent);<br>    copyBtn.textContent = &#39;Copied!&#39;;<br>    setTimeout(() =&gt; (copyBtn.textContent = &#39;Copy&#39;), 2000);<br>  } catch {<br>    copyBtn.textContent = &#39;Press Ctrl+C&#39;;<br>  }<br>});</pre><p><strong>navigator.clipboard.writeText()</strong> returns a promise, so you can confirm it worked and update the button or show a fallback message if it didn’t. It only works in response to a real user action like a click, which is the correct behavior — you don’t want pages silently writing to your clipboard.</p><p>The old approach involved creating a hidden text field, selecting it, and calling a now-deprecated command. This is so much cleaner.</p><h3>A Quick Honesty Check</h3><p>I want to be clear about something, because I’m still figuring this out myself: this isn’t “<strong>frameworks bad, vanilla good.</strong>”</p><p>Frameworks exist for good reasons. When an app gets big, with lots of pieces of state that all need to stay in sync, a framework saves you from a real mess. When a whole team is working on the same codebase, the shared structure is genuinely valuable. The point isn’t to avoid tools — it’s to actually know what the browser can do, so that when you reach for something extra, it’s because you need it and not just out of habit.</p><p>For a fade-in animation or a copy button, you probably don’t need it. For a full dashboard with complex shared state, you very well might. Knowing the difference is the skill I’m trying to build.</p><h3>Takeaways</h3><ul><li><strong>Before installing</strong> a package, check whether the browser already does it. A lot of older advice predates features that now ship natively.</li><li><strong>&lt;dialog&gt; gives you an accessible modal </strong>— focus trapping, Escape, and a backdrop — almost for free.</li><li><strong>Intersection Observer</strong> handles scroll animations and infinite scroll without scroll-event performance headaches.</li><li><strong>The Clipboard API</strong> replaces the old hidden-textarea hack with a clean promise-based call.</li><li><strong>Native features</strong> cost zero bundle size and come with accessibility built in, which matters more than it gets credit for.</li><li><strong>None of this </strong>means frameworks are bad — it means you can choose them on purpose instead of by reflex.</li></ul><p><em>Sofia is a junior frontend developer with a growing passion for building accessible and user-friendly web experiences. She is currently expanding her skills in JavaScript and React while exploring modern frontend development practices.</em></p><p><em>Driven by curiosity and a commitment to continuous learning, Sofia enjoys creating inclusive digital experiences and advocates for web accessibility to ensure technology is usable by everyone.</em></p><p><em>Beyond coding, Sofia volunteers with Frontend Queens, supporting and encouraging others on their web development journey while continuing to grow as a developer.</em></p><p><em>She is excited to continue learning, building, and helping the frontend community.</em></p><p>You can follow Sofia on <a href="https://www.linkedin.com/in/sofia-hilans-044583385/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=299924186b78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Interview Prep: Solving the LeetCode “Join Two Arrays by ID” Challenge]]></title>
            <link>https://medium.com/@frontendqueens/javascript-interview-prep-solving-the-leetcode-join-two-arrays-by-id-challenge-5c6d4a302ee9?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c6d4a302ee9</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-array-methods]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 14:02:16 GMT</pubDate>
            <atom:updated>2025-12-02T14:02:16.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*e0TjlNiRQ3qnk5K8DVNRBg.png" /></figure><p>Working with JSON often means dealing with multiple data sources. One API may return a list of users while another may return the user details. Or you might have products in one array and inventory information in another. In real world applications, data rarely arrives as a complete package; we often have to combine it.</p><p>One common pattern is joining two arrays by a shared key such as an <em>id</em>. This mirrors the idea of a JOIN in SQL, but in JavaScript we perform the operation manually. This merging pattern is also a simplified version of what happens in API orchestration. When different services return related data, the backend must combine those responses into one coherent JSON output, typically by matching items on a shared identifier.</p><h3>Problem</h3><p>You are given two arrays of objects and you need to return a single merged array. The objects in the arrays will have an <em>id</em> and the arrays should be merged by the shared <em>id</em>.</p><pre>const arr1 = [<br>  { id: 1, name: &#39;Alice&#39;, role: &#39;user&#39; },<br>  { id: 2, name: &#39;Bob&#39;, role: &#39;admin&#39; },<br>  { id: 3, name: &#39;Charlie&#39;, role: &#39;guest&#39; }<br>];<br><br>const arr2 = [<br>  { id: 2, role: &#39;superadmin&#39; },<br>  { id: 4, name: &#39;David&#39;, role: &#39;user&#39; }<br>];</pre><p>If an <em>id </em>is present in only one of the arrays, the corresponding object should be included in the merged output as is. When both arrays contain an object with the same <em>id</em>, the values in the second array take precedence and overwrite those in the first. This mirrors how the JavaScript spread operator works when merging objects.</p><p>The merged array should look like this:</p><pre>[<br>  { id: 1, name: &#39;Alice&#39;, role: &#39;user&#39; },<br>  { id: 2, name: &#39;Bob&#39;, role: &#39;admin&#39; },<br>  { id: 3, name: &#39;Charlie&#39;, role: &#39;guest&#39; },<br>  { id: 2, role: &#39;superadmin&#39; },<br>  { id: 4, name: &#39;David&#39;, role: &#39;user&#39; }<br>];</pre><p>The resultant merged array should have the following features:</p><ul><li>Combine objects with the same id.</li><li>Prefer values from the second array if the keys collide</li><li>Sort the array by <em>id </em>(in ascending order)</li></ul><h3><strong>Implementation</strong></h3><p>There are several ways to solve this problem: using a loop with the find method, using reduce, or using a Map, among others. Each approach works, but the Map method tends to be one of the cleanest and most efficient. Before we explore that approach in detail, let’s briefly look at some of the alternative solutions.</p><p><strong>Loop + find()</strong></p><p>In this approach, we iterate through one array and look for the matching object in the other array using find(). Though this approach is easy to understand and beginner friendly, the find method inside the loop has O(n²) complexity and is slow for larger arrays.</p><p><strong>Using reduce()</strong></p><p>This method is more functional and compact because it processes the first array and builds an accumulator object keyed by id. It uses reduce() to construct an object in the form { id: mergedObject }, then merges objects from both arrays into the accumulator, ensuring that values from the second array override those from the first when IDs match. Finally, the accumulator’s values are converted back into an array to produce the merged result. Though this approach avoids nested loops, it is not as efficient as using Maps.</p><p><strong>Using Map</strong></p><p>For this implementation, we’ll use the Map() method, which is one of the cleanest and most efficient ways to join two arrays by ID. The approach is straightforward: first, create a new Map() and insert all objects from the first array, using their id as the key. Next, merge the objects from the second array into the same map. This ensures that if two objects share the same id, the values from the second array override the ones from the first. Once all entries are merged, convert the map’s values back into an array and sort it if needed to produce the final result. This method is fast and elegant, with the major advantage of offering O(n) lookup and merge performance while keeping the code readable. The only downside is that it introduces the extra Map() structure, which slightly increases memory usage, though this trade-off is generally worth it for clarity and efficiency.</p><pre>var join = function (arr1, arr2) {<br>  const map = new Map();<br>  // Insert all objects from the first array into the map<br>  for (const obj of arr1) {<br>    map.set(obj.id, { ...obj });<br>  }<br>  // Merge objects from the second array into the map<br>  for (const obj of arr2) {<br>    map.set(obj.id, { ...map.get(obj.id), ...obj });<br>  }<br>  // Convert the map values back to an array<br>  return Array.from(map.values()).sort((a, b) =&gt; a.id - b.id);<br>};</pre><p><strong>Performance comparison</strong></p><figure><img alt="performance comparison" src="https://cdn-images-1.medium.com/max/674/1*rHq2xinYhTea0eRGemcoTw.png" /></figure><p>Real-world data is rarely clean, so it’s important to understand how the “join two arrays by ID” pattern behaves in edge conditions.</p><p>Here are some situations you may encounter:</p><p>1.<strong> Both arrays are empty</strong></p><p>There’s nothing to merge, so the result should simply be an empty array. This is a good base case to test, especially when dealing with optional API responses.</p><p>2. <strong>One array is empty</strong></p><pre>const arr1 = []<br><br>const arr2 = [<br>  { id: 2, role: &#39;superadmin&#39; },<br>  { id: 3, name: &#39;Charlie&#39;, role: &#39;user&#39; },<br>];</pre><p>If arr1 is empty, the output should be equivalent to arr2, and vice-versa. This commonly occurs when a service returns partial data or when a feature flag disables one dataset.</p><p><strong>Resulting array:</strong></p><pre>[<br>  { id: 2, role: &#39;superadmin&#39; },<br>  { id: 3, name: &#39;Charlie&#39;, role: &#39;user&#39; },<br>];</pre><p>3. <strong>IDs have different types (string vs number)</strong></p><p>One array might have “2” while the other has 2.</p><p>Without normalization, these become different IDs.</p><pre>const arr1 = [<br>  { id: 1, name: &#39;Alice&#39;, role: &#39;user&#39; },<br>  { id: &quot;2&quot;, name: &#39;Bob&#39;, role: &#39;admin&#39; },<br>]<br><br>const arr2 = [<br>  { id: 2, role: &#39;superadmin&#39; },<br>  { id: 3, name: &#39;Charlie&#39;, role: &#39;user&#39; },<br>];</pre><p>Resulting array</p><pre>[<br>  { id: 1, name: &#39;Alice&#39;, role: &#39;user&#39; },<br>  { id: &quot;2&quot;, name: &#39;Bob&#39;, role: &#39;admin&#39; },<br>  { id: 2, role: &#39;superadmin&#39; },<br>  { id: 3, name: &#39;Charlie&#39;, role: &#39;user&#39; },<br>];</pre><p>A robust implementation converts all IDs to a consistent type before merging.</p><p>4.<strong> Arrays contain null or malformed objects</strong></p><p>APIs occasionally return null, undefined, or objects missing the id field.</p><p>Your function should guard against this to avoid runtime errors or unexpected overwrites.</p><h3><strong>Conclusion</strong></h3><p>Joining two arrays by ID is a fundamental data manipulation skill that appears everywhere in real-world development. Whether you’re combining API responses, enriching dashboard data, reconciling records, or performing the JavaScript equivalent of a database join, this pattern becomes part of your everyday toolkit. Understanding multiple approaches and knowing when to choose each one strengthens one’s ability to work with complex JSON structures confidently and efficiently.</p><h3>About the Author</h3><p><strong>Deepthi Nair </strong>is a passionate React and Next.js developer interning remotely. She loves building clean, user-friendly web apps and continuously learn new tools and technologies. Excited to grow, collaborate, and contribute to meaningful projects.</p><p>You can connect with <strong>Deepthi</strong> on <a href="http://www.linkedin.com/in/deepthijnair">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c6d4a302ee9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Interview Prep: Building the Array .last() Prototype]]></title>
            <link>https://medium.com/@frontendqueens/javascript-interview-prep-building-the-array-last-prototype-498035ef0110?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/498035ef0110</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 14:03:06 GMT</pubDate>
            <atom:updated>2025-11-25T14:03:06.682Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Interview Prep: Building the Array .last() Prototype</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opyUKEgSE3fu9RG8dd_HfA.png" /></figure><p>If you’ve ever explored JavaScript challenges on LeetCode, you might have noticed a section called “<strong>JSON”</strong>. Though at first it sounds like we are going to parse through JSON strings, we are going to delve into deeper and more practical problems, such as manipulating JavaScript objects and arrays, the same structure that powers real-world JSON data.</p><p>One of the simplest and most insightful problems in LeetCode is the <strong><em>“Array Prototype Last”</em></strong>. In this problem, you are asked to write a method that would enhance all the arrays such that when the <strong>.last()</strong> method is called on any array, it would return the last element of the array, provided the array is not empty. If the array is empty, it should return -1.</p><p>Let’s see how we can approach the problem. But before that, let’s understand what prototypes are</p><h3><strong>What are Prototypes in JavaScript?</strong></h3><p>The dictionary definition of a prototype is:</p><p>“<em>a first, typical or preliminary model of something, especially a machine, from which other forms are developed or copied.</em>”.</p><p>In JavaScript, a prototype serves a similar purpose: it’s a sort of blueprint from which objects and arrays inherit the shared behavior and properties. In short, a prototype allows JavaScript to implement inheritance where objects and arrays can inherit shared methods without duplicating them.</p><p>By extending the prototype, we can add custom methods that will automatically be available to every array in the program.</p><h3><strong>Why is this problem in the JSON category?</strong></h3><p>Even though we are not directly parsing JSON here, arrays are a core part of JSON data. In a typical web application, data is often transferred between server and client using JSON. On the client side, the JSON string is received as part of the API response from the server, which would often be in the form of an array of objects.</p><p>For example, user lists, product lists, message feeds, etc. When you want to retrieve the last product/item in the list or the last message from the feed, we use the logic for this problem that we will be addressing soon.</p><p>Therefore, through this problem, we are not just discussing a coding problem, but tackling some real world data handling scenario in disguise.</p><h4><strong>Problem Walkthrough</strong></h4><p>In this Problem, we need to write a custom method to retrieve the last element of the array.</p><p>Let’s assume an array of numbers.</p><p><strong><em>const nums = [1,2,3,4]</em></strong></p><p>Now we need to retrieve the last element. Normally, we would retrieve the last element like this:</p><p><strong><em>nums[nums.length — 1]</em></strong></p><p>Where, <strong><em>nums.length</em> </strong>will give you the total length of the array, which in our case is 4, and since arrays are indexed from 0 with the first element at position 0, the last element in our case is at position 3, and hence <strong><em>nums.length — 1</em></strong><em>. </em>To access the number at position 3, we would give nums[nums.length-1].</p><p>Though this works, it is not an elegant way to be used every time for an array of items. How about being able to retrieve the last element using something like this:</p><p><strong><em>nums.last();</em></strong></p><p>This is where Arrays. prototype comes into picture, where we can call the .last() method on any array and it would return the last element and -1 if the array is empty.</p><p><strong>Basic implementation</strong></p><p>Let’s define the .last() method.</p><pre>Array.prototype.last = function() {<br>  if (this.length === 0) {<br>    return -1;<br>  }<br>  return(this[this.length - 1]);<br>}</pre><p>Here, <strong><em>this</em></strong><em> </em>refers to the array instance that calls the .last() method. We check if the length of the given array is equal to 0. If it is, -1 is returned. If not, the last element indexed at (total length of the array — 1) is returned.</p><p>That’s it! We’ve just extended JavaScript’s built-in Array.</p><p><strong>Why this matters</strong></p><p>When you work with JSON data, you often get arrays like this:</p><pre>const response ={<br>  users: [<br>    {id:1, name:&quot;Alice&quot;},<br>    {id:2, name:&quot;Bob&quot;},<br>    {id:3, name:&quot;Charlie&quot;}<br>  ]<br>}</pre><p>If you want to access the last user:</p><pre>response.users.last()<br>// id:3, name:&quot;Charlie&quot;</pre><p>Now you can retrieve the last item without having to repeat the array indexing logic. This JSON problem is not just a coding exercise but a real-world data pattern</p><p>Understanding prototypes helps demystify how JavaScript actually works under the hood. By adding a simple method like .last() to Array. prototype, you can see how all arrays instantly gain access to shared behavior through inheritance.</p><p>This approach keeps JavaScript efficient, consistent, and flexible, especially when working with data structures that mirror real-world JSON. Grasping this concept gives you a stronger foundation for writing cleaner, more expressive, and more powerful JavaScript.</p><h3>About the Author</h3><p><strong>Deepthi Nair </strong>is a passionate React and Next.js developer interning remotely. She loves building clean, user-friendly web apps and continuously learn new tools and technologies. Excited to grow, collaborate, and contribute to meaningful projects.</p><p>You can connect with <strong>Deepthi</strong> on <a href="http://www.linkedin.com/in/deepthijnair">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=498035ef0110" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Intuition to Proficiency: Function Transformations in JavaScript]]></title>
            <link>https://medium.com/@frontendqueens/from-intuition-to-proficiency-function-transformations-in-javascript-bade547e78d5?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bade547e78d5</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 14:26:47 GMT</pubDate>
            <atom:updated>2025-11-11T14:26:47.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Banner" src="https://cdn-images-1.medium.com/max/680/1*xCIFo-1zkB2QcR0XNr5X5w.png" /></figure><p><em>Two thoughtful challenges to build control, confidence, and flow in our code.</em></p><h3>💬 From Practice → Proficiency</h3><p>Last time, we built the muscle of intuition. We practiced setting up flows, transforming, and composing functions. But intuition becomes true skill when we test it from different angles. In this post, we’ll solidify that knowledge by solving two more LeetCode problems that deepen our understanding.</p><p>Function transformations aren’t just clever tricks — whether we’re limiting how often something runs, chaining transformations, or wrapping behavior with safeguards, we’re essentially teaching functions to <em>adapt</em>.</p><h3>🧩 Leetcode #2666 — Allow Once Function Call</h3><p><strong>Mental model: A function that locks itself after one use.<br></strong>Think about a “Submit” button on a form. You click it once, and the form submits. Click it again? Nothing happens. That’s the pattern we’re exploring here.</p><p><strong>🧠 The Problem</strong></p><p>Given a function `fn`, return a new function that ensures `fn` is called at most once.<br> — The first call returns the result.<br> — Every subsequent call returns `undefined`.</p><pre>// Example<br>Input: fn = (a,b,c) =&gt; (a + b + c), calls = [[1,2,3],[2,3,6]]<br>Output: [{&quot;calls&quot;:1,&quot;value&quot;:6}]</pre><p><strong>🎯 Your Turn First</strong></p><p>Before scrolling ahead, pause and think about how you’d approach this.<br> — What would you need to <em>remember</em> between calls?<br> — Where would that “memory” live?</p><p>Try sketching your own version — even a rough one — before looking at the solution. The act of thinking it through builds the neural link between understanding and intuition.</p><p>🔍 <strong>Breaking Down the Solution</strong></p><p>Here’s one clean way to implement it…</p><pre>var once = function(fn) {<br> let hasBeenCalled = false;<br> <br> return function(...args) {<br> if (!hasBeenCalled) {<br> hasBeenCalled = true;<br> return fn.call(this, ...args);<br> }<br> return undefined;<br> }<br>};</pre><p><strong>🧩 The Closure</strong></p><p>The variable hasBeenCalled lives inside the closure created by our wrapper function. It doesn&#39;t reset between calls — instead, it <em>remembers</em> the state from the previous call. Think of it as a lock.</p><pre>let hasBeenCalled = false;</pre><p><strong>🚀 Returning a New Function</strong></p><p>— once creates and returns a new wrapper function<br>— This wrapper has access to fn (the original function)<br>— The ...args Syntax captures any arguments passed to the wrapper<br>— Inside, we pass those arguments along to fn using fn(...args)</p><pre>return function(...args) { // … }</pre><p><strong>⚙️ Conditional Logic</strong></p><p>On the first call, hasBeenCalled is false, so the condition passes — we flip the flag to true and run the original function.</p><p>On every call after that, the condition fails and the function quietly returns undefined.</p><blockquote><strong><em>Why undefined?</em></strong><em> It’s a silent contract: “I heard you, but I’m choosing not to act.” Better than throwing an error (too aggressive) or returning the old result (misleading).</em></blockquote><pre>if (!hasBeenCalled) {<br> hasBeenCalled = true;<br> return fn.call(this, ...args);<br>}<br>return undefined;</pre><h3>🔀 From “Run Once” → “Don’t Repeat Work”</h3><p>Once we’ve learned to stop unnecessary calls, the next logical step is avoiding redundant <em>work</em> — that’s where memoization shines.</p><p>In the last problem, we set a <strong>boundary on execution</strong>: <em>run at most once</em>.<br>Now we’ll set a <strong>boundary on effort</strong>: <em>if you’ve already computed this, don’t do it again</em>.</p><p>That’s <strong>memoization</strong> — one of the simplest yet most powerful optimization patterns in programming.</p><h3>🧩 LeetCode #2623 — Memoize</h3><p>The challenge: build your own cache layer.</p><p><strong>🧠 The Problem</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IfcI0g6GDtqNIpxo" /></figure><p>Given a function fn, return a memoized version of that function. A <strong>memoized </strong>function is a function that will never be called twice with the same inputs. Instead it will return a cached value.</p><p>You may encounter three possible input functions in the test cases:<br>• <strong>sum(a, b)</strong> → returns a + b<br>• <strong>fib(n)</strong> → returns 1 if n &lt;= 1, otherwise fib(n — 1) + fib(n — 2)<br>• <strong>factorial(n)</strong> → returns 1 if n &lt;= 1, otherwise factorial(n — 1) * n</p><p>🎯 <strong>Your Turn First</strong></p><p>Before you scroll down, think about:<br>• Where will you store results that need to persist between calls?<br>• How will you create a reliable, unique <em>key</em> from a list of arguments?<br>• And what happens if the same function is called with reordered arguments, like (2,3) and (3,2)?</p><p>Sketch your logic in your mind — that act of mental rehearsal builds intuition.</p><p>🔍 <strong>Breaking Down the Solution</strong></p><p>Here’s a clean implementation:</p><pre>function memoize(fn) {<br> const cache = {};<br> <br> return function(...args) {<br> const key = JSON.stringify(args);<br> <br> if (key in cache) {<br> return cache[key]; // Cache hit - skip computation<br> }<br> <br> const result = fn(...args); // Cache miss - compute now<br> cache[key] = result; // Store for next time<br> return result;<br> }<br>}</pre><p><strong>🗄️ The Cache</strong></p><p>This time, our closure holds more than a simple flag. It holds a <strong>cache object</strong> that maps argument patterns to their computed results.</p><pre>const cache = {};</pre><p>Each time the function runs, it checks: <em>“Have I seen these exact inputs before?”</em> If yes, return the stored answer. If no, compute it, store it, then return it.</p><p><strong>🔑 Creating a Key</strong></p><p>The trickiest part: how do you turn (2, 3, 5) into something you can use as a lookup key?</p><pre>const key = JSON.stringify(args);</pre><p>JSON.stringify() converts the arguments array into a string like &quot;[2,3,5]&quot;. This gives us a consistent, unique identifier for each set of inputs.</p><p><strong>⚠️ A subtle gotcha</strong></p><p>This approach treats (2,3) and (3,2) as <em>different</em> inputs — which is correct for most functions. Example: subtract(5,3) and subtract(3,5) should return different results.</p><p>⚙️<strong> Step-by-Step Flow</strong></p><p>1️⃣ First call: cache is empty → run fn, store the result.<br>2️⃣ Subsequent call with the same arguments → return cached result instantly.<br>3️⃣ Different arguments → compute again and add to the cache.</p><p><strong>🎭 Seeing It In Action</strong></p><p>Let’s trace through a memoized Fibonacci call:</p><pre>const memoizedFactorial = memoize(factorial);<br>memoizedFactorial(5);  // Computes: 5×4×3×2×1, caches result<br>memoizedFactorial(5);  // Returns cached result instantly<br>memoizedFactorial(4);  // Computes: 4×3×2×1 (separate cache entry)</pre><p>Each unique set of arguments gets its own cache entry:<br> — First call: factorial(5) → computes and caches<br>— Second call: factorial(5) → returns cached result instantly<br>— Different input: factorial(4) → computes independently</p><p>🛑 <strong>Watch Out For</strong></p><p>❌ Don’t reinitialize the cache inside the returned function — it must persist between calls.<br>❌ And remember: (2,3) and (3,2) are different inputs.</p><h3>🧭 Wrapping Up</h3><p>Across these two problems, we explored two sides of the same principle: <strong>control</strong>.</p><p>• In <em>Allow Once</em>, we learned to control <em>when</em> a function runs.<br>• In <em>Memoize</em>, we learned to control <em>how often</em> it works.</p><p>Both draw their strength from <strong>closure</strong> — a function’s quiet ability to remember.</p><pre>💡 **Rule of Thumb**<br>once(fn) → run only once<br>memoize(fn) → run many times, compute once per unique input</pre><p>And these don’t just help during interviews; they power real systems:</p><p>• <strong>Backend:</strong> caching database queries and API responses<br>• <strong>Frontend:</strong> React’s useMemo and useCallback preventing re-renders<br>• <strong>Everyday JS:</strong> memoized selectors, throttled handlers, optimized loops</p><p>Small patterns compound into deep fluency.</p><p>We practice writing code that feels intentional and elegant — moving from merely solving problems to <em>crafting</em> solutions.<br>Now, try implementing once with a twist: make it reset after 5 seconds.</p><h3>About the Author</h3><p><strong>Anju Karanji</strong> is a full-stack engineer with experience at Amazon and fast-growing startups, building performant and intuitive web applications with React, TypeScript, and Node.js. Originally from India and now based in the U.S., she’s passionate about writing clean, elegant code and empowering more women to find confidence in tech.<br>Outside of work, she enjoys writing, reading about mindfulness, and spending time with her daughter. You can connect with Anju on <a href="https://www.linkedin.com/in/anju-karanji">LinkedIn</a> or visit <a href="https://www.anjukaranji.com/">anjukaranji.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bade547e78d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Composition in JavaScript: Building Intuition Through Practice]]></title>
            <link>https://medium.com/@frontendqueens/function-composition-in-javascript-building-intuition-through-practice-e73b2706013d?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e73b2706013d</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 14:02:03 GMT</pubDate>
            <atom:updated>2025-11-04T14:02:59.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uldbdqY_YAWcyD3P_jaIuA.jpeg" /></figure><h3>💬 From Concept → Intuition</h3><p>In <a href="https://medium.com/@frontendqueens/function-transformations-in-javascript-from-bind-to-composition-cdbfe0b52618">Part 1</a>, we explored function transformations — bind, curry, and compose.</p><p>Now it’s time to put them into practice by solving two LeetCode problems that build on these ideas.</p><p>These patterns aren’t something we memorize; they’re something we <em>feel</em> over time. The goal here isn’t to get them perfect — it’s to build intuition.</p><p>So when a similar question shows up in an interview, our brain just recognizes the shape of it and knows where to start.</p><p>We’ve all chained small actions together to get something done…<br>Brewing coffee means <em>grind beans → pour milk → add sugar.</em></p><p>Composition works the same way: small functions combined in sequence, where the output of one becomes the input of the next.</p><p>In JavaScript, we compose small, focused functions and design their flow. Maybe one function doubles a number, another squares it, and another adds one.</p><pre>const double = x =&gt; x * 2;<br>const square = x =&gt; x * x;<br>const addOne = x =&gt; x + 1;</pre><pre>// Manually composing (messy):<br>const result = addOne(square(double(4))); // 65</pre><pre>// What we&#39;ll build:<br>const transform = compose([addOne, square, double]);<br>transform(4); // 65</pre><p>Notice the order? We apply functions <strong>right to left</strong>: double(4) → 8 → square(8) → 64 → addOne(64) → 65.<br>That’s the core of composition.</p><h3>🧩 LeetCode #2629 — Function Composition</h3><p><strong>The problem:<br></strong>Given an array of functions [f1, f2, f3, …], return a new function that represents their composition.<br>The composition of functions [f, g, h] is defined as f(g(h(x))).<br>If the array is empty, return the identity function f(x) = x.</p><p><strong>Implementation:</strong></p><pre>/**<br>* @param {Function[]} functions<br>* @return {Function}<br>*/</pre><pre>var compose = function (functions) {<br>  return function (x) {<br>    let res = x;<br>    let i = functions.length - 1;<br>    while (i &gt;= 0) {<br>      res = functions[i](res);<br>      i --;<br>    }<br>    return res;<br>  }<br>};</pre><p><strong>🔍 Breaking Down the Solution:</strong></p><p><strong>The outer function</strong> receives an array of functions and returns a new function. That returned function is what we’ll actually call with a value.</p><p>The structure: We’re creating a function that <em>builds</em> another function. Think of it like a function factory. When we call compose([addOne, square, double]), we&#39;re not running those functions yet. We&#39;re just packaging them together and returning a brand new function that knows how to run them.</p><p>Inside the returned function, we start with the value we’re given: let res = x. Then i points to the last function in the array (the rightmost one). The loop does the real work: it keeps applying each function to the current result, moving left one step at a time.</p><pre>while (i &gt;= 0) {<br> res = functions[i](res); // Apply current function to result<br> i--; // Move to the previous function (going left)<br>}</pre><p>By the end of the loop, res has flowed through every function in the chain from right to left and holds the final transformed value.</p><p><strong>🧠 Let’s Trace It</strong></p><p>compose([addOne, square, double])(4)</p><p>Press enter or click to view image in full size</p><figure><img alt="function results" src="https://cdn-images-1.medium.com/max/700/0*nhobIiVaUivzxfMK.png" /></figure><p>Return value → <strong>65</strong></p><p><strong>⚙️ Edge Case: Empty Array</strong></p><p>What happens if functions = []?<br>Our loop never runs (since i = -1 immediately), so we just return res = x.</p><p><strong>🚫 Common Mistakes</strong></p><p>❌ Going left to right instead of right to left</p><pre>for (let i = 0; i &lt; functions.length; i++) {<br> res = functions[i](res); // Wrong direction<br>}</pre><p>❌ Not returning a function</p><pre>var compose = function (functions) {<br>  let res = 0;<br>  // ...<br>  return res; // ❌ Should return a function, not a value<br>};</pre><h3>🔁 A Pivot</h3><p>Now that we’ve built the compose function from scratch, let’s shift gears to another small but common pattern — working with <strong>function parameters.</strong></p><p>While this next problem doesn’t involve composition directly, it tests how well we understand JavaScript’s handling of arguments — something that comes up constantly when writing or debugging higher-order functions.</p><h3>🧩 LeetCode #2703 — Return Length of Arguments Passed</h3><p>Write a function argumentsLength that returns the count of arguments passed to it.</p><pre>argumentsLength(5); // 1<br>argumentsLength({}, null, “3”); // 3</pre><h3>The Trap</h3><p>When we first see this, we might think we need to loop through arguments and count them manually. But JavaScript already gives us what we need.</p><pre>var argumentsLength = function(…args) {<br>  return args.length;<br>};</pre><p><strong>What’s happening here?</strong></p><p>The rest parameter syntax (…args) collects all arguments into an array. Once we have an array, we just use its .length property — that’s it.</p><h3>🧭 Wrapping Up</h3><p>We covered two essential aspects of working with functions in JavaScript. First, we built a compose function that chains transformations — a pattern used in <strong>middleware</strong>, <strong>data pipelines</strong>, and <strong>React’s render flow</strong>.</p><p>Then, we explored how JavaScript handles function parameters — a subtle concept that powers every higher-order function.<br>The real skill isn’t memorizing syntax — it’s <em>recognizing patterns. </em>These intuitions build over time through practice.</p><p>Keep solving, keep noticing, and you’ll find yourself thinking in transformations naturally.</p><h3>🚀 What’s Next</h3><p>In the next post, we’ll explore <strong>function wrappers</strong> — another transformation pattern that shows up everywhere from API clients to error handling in production code.</p><h3>About the Author</h3><p><strong>Anju Karanji</strong> is a full-stack engineer with experience at Amazon and fast-growing startups, building performant and intuitive web applications with React, TypeScript, and Node.js. Originally from India and now based in the U.S., she’s passionate about writing clean, elegant code and empowering more women to find confidence in tech.<br>Outside of work, she enjoys writing, reading about mindfulness, and spending time with her daughter. You can connect with Anju on <a href="https://www.linkedin.com/in/anju-karanji">LinkedIn</a> or visit <a href="https://www.anjukaranji.com/">anjukaranji.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e73b2706013d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Transformations in JavaScript — from bind to Composition]]></title>
            <link>https://medium.com/@frontendqueens/function-transformations-in-javascript-from-bind-to-composition-cdbfe0b52618?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdbfe0b52618</guid>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 14:02:56 GMT</pubDate>
            <atom:updated>2025-10-28T14:02:56.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>Function Transformations in JavaScript — from bind to Composition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*uQxxzjyNi6-5gzarNQTv3Q.png" /></figure><p><em>Ever wondered why React’s useState works the way it does? Or how Redux middleware chains actions together? These aren’t magic — they’re function transformations, and you’ve been using them all along.</em></p><p>In JavaScript, functions are incredibly flexible. You can store them in variables, pass them around like any other value, and even transform them into new functions with different behaviors. Basically, we treat functions as first-class citizens. We reshape functions. Not just <em>what</em> functions do, but <em>how</em>, <em>when</em>, and <em>where</em> they execute.</p><p>There are two broad categories of function transformation:</p><p><strong>Language-level transformations</strong> manipulate a function’s execution context or arguments using built-in methods like bind, call, and apply.</p><p><strong>Design-level transformations</strong> reshape function behavior itself through techniques like composition, currying, and partial application.</p><p>Let’s explore both — starting with how JavaScript lets us control function context.</p><p><strong>1️⃣ Transforming Function Contexts: call, apply, and bind</strong></p><p>JavaScript’s <em>this</em> keyword is both powerful and flexible. The methods <strong>call</strong>, <strong>apply</strong>, and <strong>bind</strong> let us control which object a function treats as its context, giving us precise control over execution.</p><p><strong>Why do these still matter in 2025?</strong></p><p>You might be thinking: “I work in React or Next.js. Context is handled for me.”<br>True. But understanding these methods is still valuable:<br>-&gt; They’re foundational to how <em>this</em> works in JavaScript.<br>-&gt; Event listeners and callbacks often rely on context binding.<br>-&gt; They deepen our understanding of closures and arrow functions.<br>-&gt; Under the hood, many libraries use call or apply to invoke callbacks dynamically.<br>-&gt; They build mental models for higher-order functions and functional patterns</p><p>Let’s look at a tiny example. We’ll make a simple `greet` function that says hello — then see how we can change *who* it greets by transforming its context.</p><pre>const person = { <br> name: ‘Jack’, <br> greet(greeting) { <br> console.log(`${greeting}, ${this.name}!`); <br> }, <br>}; <br> <br>const anotherPerson = { name: ‘Rose’ }; <br> <br>// Default call <br>person.greet(‘Hi’); // “Hi, Jack!” <br> <br>// call → execute immediately with new context <br>person.greet.call(anotherPerson, ‘Hello’); // “Hello, Rose!” <br> <br>// apply → same as call, but args as an array <br>person.greet.apply(anotherPerson, [‘Namaste’]); // “Namaste, Rose!” <br> <br>// bind → returns a new function with bound context <br>const greetRose = person.greet.bind(anotherPerson, ‘Hey’); <br>greetRose(); // “Hey, Rose!”</pre><p><em>The Key Difference </em><strong><em>call</em></strong><em> and </em><strong><em>apply</em></strong><em> </em><strong><em>invoke the function immediately</em></strong><em>, while </em><strong><em>bind</em></strong><em> </em><strong><em>returns a new function</em></strong><em> with its context permanently locked.</em></p><p>In other words, bind doesn’t just execute — it creates a <em>transformed version</em> of the original function with a different identity but shared logic.</p><p><strong>2️⃣ Design-Level Transformations: Currying, Partial Application, and Composition</strong></p><p>While <strong>call</strong>, <strong>apply</strong>, and <strong>bind</strong> help us control <em>where</em> a function runs, these next patterns help us control <em>how</em> it behaves.</p><p>You’ll see these three ideas pop up everywhere — and once you spot them, they start making total sense:</p><p><strong>🍰 Currying</strong></p><p><strong>Why learn this?</strong> It helps you build reusable function “templates” that you can customize later.<br>Think of currying as taking things one step at a time.<br>Instead of dumping every ingredient into a recipe at once, you add one, stir, then add the next.</p><pre>// Regular function<br>function add(a, b, c) {<br>  return a + b + c;<br>}<br>add(1, 2, 3); // 6</pre><p>A curried version handles one piece at a time:</p><pre>function curriedAdd(a) {<br> return function (b) {<br> return function © {<br> return a + b + c;<br> };<br> };<br>}<br>curriedAdd(1)(2)(3); // 6<br>// Or shorter with arrows<br>const curriedAdd = a =&gt; b =&gt; c =&gt; a + b + c;</pre><p>The cool part? You can stop halfway and save that partially-finished function to reuse later.</p><p><strong>Why is this useful?</strong><br>Currying allows you to create specialized versions of functions. Think of it as saying: “<em>I already know the first part — I’ll fill in the rest later.”</em></p><pre>const addOne = curriedAdd(1);<br>const addOneAndTwo = addOne(2);</pre><pre>addOneAndTwo(3); // 6<br>addOneAndTwo(10); // 13</pre><p><strong>🧩 Partial Application</strong></p><p><strong>Why learn this?</strong> Ever wish you could “save” some arguments and reuse them? That’s what this does.<br>Have you ever created a reusable helper that already knows part of what to do? That’s partial application. You give a function some info up front, and it remembers it.<br>Partial application is similar to currying, but instead of returning a chain of single-argument functions, it “pre-fills” some arguments and returns a function waiting for the rest.</p><pre>// Regular JavaScript function<br>function greet(greeting, name, punctuation) {<br>  return `${greeting}, ${name}${punctuation}`;<br>}</pre><p>We can “pre-fill” the greeting:</p><pre>// Using bind we fill the greeting part</pre><pre>// We use &#39;null&#39; because greet doesn&#39;t use &#39;this&#39;<br>const sayHello = greet.bind(null, ‘Hello’);<br>sayHello(&#39;Alice&#39;, &#39;!&#39;); // &quot;Hello, Alice!&quot;<br>sayHello(&#39;Bob&#39;, &#39;.&#39;); // &quot;Hello, Bob.&quot;</pre><p>Or make a small helper to do it in a more flexible way:</p><pre>function partial(fn, …fixedArgs) {<br> return (…remainingArgs) =&gt; fn(…fixedArgs, …remainingArgs);<br>}<br>const greetCasually = partial(greet, &#39;Hey&#39;);<br>greetCasually(&#39;Charlie&#39;, &#39;!&#39;); // &quot;Hey, Charlie!&quot;</pre><p>Now greetCasually always starts with “Hey,” but you can still choose <em>who</em> to greet and <em>how</em> to punctuate. This pattern is behind tons of everyday APIs. It’s just JavaScript’s way of saying, “Don’t repeat yourself.”</p><p><strong>🧭 Function Composition</strong></p><p>In real life, we combine tiny actions to get something done.<br>In order to make coffee: pour cream → stir → add sugar. In JavaScript, we can chain tiny functions the same way.</p><p>That’s all composition really is: combining small functions so the output of one becomes the input of the next.</p><pre>const double = x =&gt; x * 2;<br>const increment = x =&gt; x + 1;<br>const square = x =&gt; x * x;</pre><pre>// Manual composition<br>const result = square(increment(double(3))); // 49<br>// 3 → 6 → 7 → 49</pre><pre>// compose uses reduceRight to apply functions right-to-left<br>const compose = (…fns) =&gt; x =&gt; fns.reduceRight((acc, fn) =&gt; fn(acc), x);<br>const transform = compose(square, increment, double);<br>transform(3); // 49</pre><pre>// Pipe helper (left to right — more intuitive)<br>const pipe = (…fns) =&gt; x =&gt; fns.reduce((acc, fn) =&gt; fn(acc), x);<br>const transformPipe = pipe(double, increment, square);<br>transformPipe(3); // 49</pre><p>We use composition everywhere: especially in data flows, React render cycles, and promise chains.</p><h3>Bringing It All Together</h3><p>Here’s a practical example combining all these concepts:</p><pre>// API response processor<br>const getUsers = data =&gt; data.users;<br>const filterActive = users =&gt; users.filter(u =&gt; u.active);<br>const mapNames = users =&gt; users.map(u =&gt; u.name);<br>const sortAlphabetically = names =&gt; names.sort();</pre><pre>const processUserData = pipe(<br> getUsers,<br> filterActive,<br> mapNames,<br> sortAlphabetically<br>);</pre><pre>const apiResponse = {<br> users: [<br> { name: ‘Charlie’, active: true },<br> { name: ‘Alice’, active: false },<br> { name: ‘Bob’, active: true }<br> ]<br>};</pre><pre>processUserData(apiResponse); // [‘Bob’, ‘Charlie’]</pre><h3>💡 Real-World Use Cases — You’re Already Doing This!</h3><p>Some of these ideas might seem abstract, but honestly, we’ve already been using them everywhere.<br>Modern tools like React, Redux, and even plain JavaScript rely on these transformations under the hood.<br>Let’s look at a few examples we all recognize 👇</p><p>⚙️<strong> React’s useState → Partial Application<br></strong>When we call useState(), it gives us two things: the current value and a setter function.<br>That setter function is pre-filled with the exact state variable it controls — meaning it’s a partially applied function. Think of it like React saying, “Here’s a button that already knows which piece of state it belongs to — you just press it.”<br>You don’t pass the state name every time — React already did the binding for you.</p><p>🔄<strong> React’s Rendering Flow → Function Composition<br></strong>When our component re-renders, React Fiber moves through clear steps:<br><strong>Render → Reconcile → Commit.</strong><br>That’s function composition in action — small steps chained together to do something bigger.</p><p>🧱<strong> Redux Middleware → The Pipe Pattern<br></strong>If you’ve ever used redux-thunk or redux-logger, you’ve seen the pipe pattern in action.<br>Each middleware function receives an action, transforms it, and passes it to the next — like a chain of pipes moving data downstream.<br>That’s function composition in action.</p><p>⛓️<strong> Promise Chains → Async Composition<br></strong>Every time you write:</p><pre>fetch(‘/api’)<br> .then(res =&gt; res.json())<br> .then(data =&gt; setUsers(data));</pre><p>you’re composing asynchronous functions.<br>Each .then() transforms the previous result before passing it along — again composition in motion.</p><p><strong>🧰 Functional Libraries → Currying Everywhere<br></strong>Libraries like <strong>Lodash/fp</strong> and <strong>Ramda</strong> curry every function by default, so you can partially apply arguments on the fly:</p><pre>map(‘name’, users);</pre><p>works because map is already curried — it returns a new function waiting for the array.</p><h3>🌈 Why It Matters</h3><p>Every time you pass a callback, pre-fill a function, or chain a promise, you’re already shaping JavaScript to your will.</p><p>The more we understand these transformations, the more expressive and creative our code becomes.</p><p>The best part? We don’t need to master all these patterns at once.<br>We’re already using them in small ways every day.</p><p>So keep experimenting, keep noticing patterns. ✨</p><h3>🚀 Where to Go From Here</h3><ul><li><strong>Try currying one of your own functions</strong> — pick a 3-argument function and curry it</li><li><strong>Build a simple pipe utility</strong> — then use it to process some data</li><li><strong>Look for these patterns in libraries you use</strong> — can you spot composition in your codebase?</li></ul><p>The best way to learn transformations isn’t reading about them — it’s recognizing them in the wild. 🌟</p><h3>About the Author</h3><p><strong>Anju Karanji</strong> is a full-stack engineer with experience at Amazon and fast-growing startups, building performant and intuitive web applications with React, TypeScript, and Node.js. Originally from India and now based in the U.S., she’s passionate about writing clean, elegant code and empowering more women to find confidence in tech.<br>Outside of work, she enjoys writing, reading about mindfulness, and spending time with her daughter. You can connect with Anju on <a href="https://www.linkedin.com/in/anju-karanji">LinkedIn</a> or visit <a href="https://www.anjukaranji.com/">anjukaranji.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdbfe0b52618" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple, Styled GitHub Profile Viewer with React & Tailwind CSS v4]]></title>
            <link>https://medium.com/@frontendqueens/building-a-simple-styled-github-profile-viewer-with-react-tailwind-css-v4-e89d98e52d40?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e89d98e52d40</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 13:01:58 GMT</pubDate>
            <atom:updated>2025-10-14T13:01:58.877Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="banner" src="https://cdn-images-1.medium.com/max/680/1*iD9iItsRHJ2HVoxQAvosdQ.png" /></figure><p>Have you been eager to create a React app that uses real data and looks pretty, but are unsure of where to start? Look no further — let’s build a <strong>GitHub Profile Viewer </strong>powered by <strong>React</strong>, <strong>Tailwind CSS v4</strong>, and <strong>Vite</strong>!</p><p>In this tutorial, you’ll learn how to:</p><ul><li>Scaffold a Vite + React project</li><li>Configure Tailwind CSS v4 (with the new @import “tailwindcss” syntax)</li><li>Fetch live data from the GitHub REST API</li><li>Style using glassmorphism and an animated gradient background</li><li>Deploy instantly to Vercel.</li></ul><p>Link to the deployed project: <a href="https://github-profile-viewer-frontendqueen.vercel.app/">https://github-profile-viewer-frontendqueen.vercel.app/</a></p><p>Link to the GitHub repo: <a href="https://github.com/lexoskeleton/github-profile-viewer-frontendqueens">https://github.com/lexoskeleton/github-profile-viewer-frontendqueens</a></p><h3>Step 1: Set Your Project Up</h3><p>To get started, open your IDE of choice and run the following commands in your terminal:</p><pre>npm create vite@latest github-profile-viewer - - template react<br>cd github-profile-viewer<br>npm install<br>npm run dev</pre><p>These commands create the React application using Vite, switch into the application folder, install the dependencies, and start the developer server.</p><p>You should now see the default Vite + React starter page at <a href="http://localhost:5173/"><strong>http://localhost:5173</strong></a></p><p><strong>Nota bene</strong>: Vite 7 + Tailwind v4 require <strong>Node 20.19+</strong> or <strong>22.12+</strong> (this project uses version 22).</p><p>If you use <strong>NVM (Node Version Manager)</strong>, you can quickly switch to a compatible version:</p><pre>nvm install 22<br>nvm use 22</pre><p>To make that version default for this project, create a .nvmrc file in your root folder. Then, anyone cloning your repo can simply run and the correct Node version will automatically be selected.</p><pre>nvm use 22</pre><h3>Step 2: Add Tailwind CSS</h3><p>Next, we’ll install Tailwind CSS. But first!</p><p><strong>What is Tailwind CSS (and why it’s awesome with React)<br></strong> Tailwind CSS is a utility-first framework that lets you build custom designs by combining small, reusable class names right in your JSX (e.g., p-6, bg-purple-500, or rounded-xl).</p><p>When paired with <strong>React</strong>, it’s incredibly efficient: you style components where you write them, avoid CSS conflicts, and keep your UI visually consistent across breakpoints. Features such as responsive layouts, animations, and dark mode all come built-in — sweet!</p><p>Now, let’s install Tailwind and its PostCSS plugin:</p><pre>npm i -D tailwindcss @tailwindcss/postcss autoprefixer</pre><p>Create the config files:</p><pre>npx tailwindcss init -p</pre><p>Then update your <strong>postcss.config.js</strong> to use the v4 plugin:</p><pre>export default {<br>  plugins: {<br>    &quot;@tailwindcss/postcss&quot;: {},<br>    autoprefixer: {},<br>    },<br>  };</pre><p>In your <strong>src/index.css</strong>, replace everything with:</p><pre>@import &quot;tailwindcss&quot;;<br> body {<br>  @apply font-sans antialiased;<br> }</pre><p>Tailwind v4 automatically includes its base, components, and utilities, so there’s no need to manually import them.</p><p>Once you restart your dev server, you should see Tailwind working.</p><h3>Step 3: Structure the App</h3><p>Let’s organize our files for a clean, scalable structure:</p><pre>src/<br>├── components/<br>│   ├── SearchForm.jsx<br>│   ├── ProfileCard.jsx<br>│   ├── RepoList.jsx<br>│   ├── RepoItem.jsx<br>│   └── StatBox.jsx<br>├── pages/<br>│   └── Home.jsx<br>├── App.jsx<br>└── main.jsx</pre><h4>Component Breakdown</h4><p>Now that we’ve planned our component structure, let’s see what each file actually contains.</p><p>1. <strong>src/main.jsx</strong></p><p>This is the <strong>entry point</strong> for your React app.It mounts everything to the DOM &amp; loads your global styles (index.css).</p><pre>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p>2. <strong>src/App.jsx</strong></p><p>App.jsx serves as the <strong>root layout</strong>. Right now, it simply renders your main page component — we’ll add design elements later.</p><pre>export default function App() {<br>  return (<br>    &lt;main&gt;<br>      &lt;Home /&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>3. <strong>src/pages/Home.jsx</strong></p><p>Home.jsx is the <strong>core logic layer</strong>. It handles user input, manages state, and renders other components. We’ll implement the GitHub API logic here in <strong>Step 4</strong>.</p><pre>const GH_API = &quot;https://api.github.com&quot;;<br><br>// --- Fetch functions will go here in Step 4 ---<br><br>export default function Home() {<br>  // state, event handlers, and render output - we’ll get there<br>}</pre><p>4. <strong>src/components/SearchForm.jsx</strong></p><p>Handles the input form where users type a GitHub username and click on the Search Button.</p><pre>export default function SearchForm({ username, setUsername, onSubmit, isLoading }) {<br>  return (<br>    &lt;form onSubmit={onSubmit} className=&quot;flex gap-2 mb-6&quot;&gt;<br>      &lt;input<br>      type=&quot;text&quot;<br>      placeholder=&quot;Search GitHub username&quot;<br>      value={username}<br>      onChange={(e) =&gt; setUsername(e.target.value)}<br>      className=&quot;flex-1 rounded-lg border border-gray-300 p-2 text-gray-900&quot;<br>      /&gt;<br>      &lt;button<br>      type=&quot;submit&quot;<br>      disabled={isLoading}<br>      className=&quot;rounded-lg bg-purple-600 px-4 py-2 text-white hover:bg-purple-700&quot;<br>      &gt;<br>      {isLoading ? &quot;Loading…&quot; : &quot;Search&quot;}<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>    );<br>}</pre><p><strong>5. src/components/ProfileCard.jsx</strong></p><p>This card displays the user’s basic information and key stats of the user we received upon Search.We’ll make it look cute later with Tailwind utilities in Step 5.</p><pre>export default function ProfileCard({ profile }) {<br>  return (<br>    &lt;div className=&quot;p-6 border rounded-lg&quot;&gt;<br>      &lt;div className=&quot;flex items-center gap-4&quot;&gt;<br>        &lt;img<br>          src={profile.avatar_url}<br>          alt={profile.login}<br>          className=&quot;w-20 h-20 rounded-full border&quot;<br>        /&gt;<br>        &lt;div&gt;<br>          &lt;h2 className=&quot;text-2xl font-bold&quot;&gt;{profile.name || profile.login}&lt;/h2&gt;<br>          &lt;p className=&quot;text-gray-700&quot;&gt;{profile.bio}&lt;/p&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;grid grid-cols-3 gap-4 mt-6&quot;&gt;<br>        &lt;StatBox label=&quot;Followers&quot; value={profile.followers} /&gt;<br>        &lt;StatBox label=&quot;Following&quot; value={profile.following} /&gt;<br>        &lt;StatBox label=&quot;Repos&quot; value={profile.public_repos} /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>6. <strong>src/components/StatBox.jsx</strong></p><p>A small, reusable component for displaying numeric stats.</p><pre>export default function StatBox({ label, value }) {<br>  return (<br>    &lt;div className=&quot;flex flex-col items-center justify-center p-4 border rounded-lg&quot;&gt;<br>    &lt;span className=&quot;text-xl font-bold&quot;&gt;{value}&lt;/span&gt;<br>    &lt;span className=&quot;text-sm text-gray-600&quot;&gt;{label}&lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>7. <strong>src/components/RepoList.jsx</strong></p><p>This is where you will list the user’s repositories.</p><pre>export default function RepoList({ repos }) {<br>return (<br>  &lt;div className=&quot;mt-8&quot;&gt;<br>    &lt;h3 className=&quot;text-xl font-semibold mb-3&quot;&gt;Repositories&lt;/h3&gt;<br>      &lt;ul className=&quot;space-y-2&quot;&gt;<br>      {repos.map((repo) =&gt; (<br>        &lt;li key={repo.id} className=&quot;p-4 border rounded-lg&quot;&gt;<br>        &lt;a<br>        href={repo.html_url}<br>        target=&quot;_blank&quot;<br>        rel=&quot;noopener noreferrer&quot;<br>        className=&quot;font-semibold text-indigo-700 hover:underline&quot;<br>        &gt;<br>        {repo.name}<br>        &lt;/a&gt;<br>        &lt;p className=&quot;text-sm text-gray-700&quot;&gt;{repo.description}&lt;/p&gt;<br>        &lt;/li&gt;<br>      ))}<br>      &lt;/ul&gt;<br>  &lt;/div&gt;<br>  );<br>}</pre><p>8.<strong>src/index.css</strong></p><p>Your single global stylesheet powered by Tailwind v4. We’ll add in the fancy styling stuff later.</p><pre>@import &quot;tailwindcss&quot;;<br>body {<br>@apply font-sans antialiased;<br>}</pre><h3>Step 4: Build the Home Component Logic &amp; Fetch GitHub Data</h3><h4><strong>Understanding the Home Component</strong></h4><p><strong>src/pages/Home.jsx</strong> is the <strong>brain</strong> of our app: it manages user input, fetches data, and decides what to render on screen.<br> Here’s what it handles:</p><h4>State Management</h4><p>At the top of the file, we define our state variables:</p><pre>const [username, setUsername] = useState(&quot;&quot;);<br>const [tokenInput, setTokenInput] = useState(&quot;&quot;);<br>const [profile, setProfile] = useState(null);<br>const [repos, setRepos] = useState([]);<br>const [page, setPage] = useState(1);<br>const [isLoading, setIsLoading] = useState(false);<br>const [error, setError] = useState(&quot;&quot;);</pre><p>Each variable tracks a specific piece of data:</p><ul><li><strong>username: </strong>the GitHub username entered by the user</li><li><strong>profile:</strong> profile info from the API</li><li><strong>repos:</strong> the user’s repositories</li><li><strong>page</strong> : current pagination index</li><li><strong>isLoading / error:</strong> for user feedback</li></ul><h4>Memoization</h4><p>To avoid recomputing values on every render, we use useMemo():</p><pre>const token = useMemo(() =&gt; {<br>const envToken = import.meta?.env?.VITE_GITHUB_TOKEN;<br>return tokenInput?.trim() || envToken || &quot;&quot;;<br>}, [tokenInput]);<br></pre><p>and to build our request headers only when the (optional) token changes:</p><pre>const headers = useMemo(() =&gt; {<br>  const h = {<br>    Accept: &quot;application/vnd.github+json&quot;,<br>    &quot;X-GitHub-Api-Version&quot;: &quot;2022-11-28&quot;,<br>  };<br>  if (token) h[&quot;Authorization&quot;] = `Bearer ${token}`;<br>  return h;<br>}, [token]);</pre><h4><strong>Search &amp; Pagination</strong></h4><p>We are going to define two helper functions: <strong><em>fetchProfile()</em></strong> and <strong><em>fetchRepos()</em></strong>, but first, here’s where we’ll implement them.</p><p>The search handler:</p><pre>async function handleSearch(e) {<br>  e.preventDefault();<br>  if (!username.trim()) return;<br>  setError(&quot;&quot;);<br>  setIsLoading(true);<br>  setProfile(null);<br>  setRepos([]);<br>  setPage(1);<br>  // we&#39;ll call fetchProfile() and fetchRepos() here next<br>}</pre><p>The pagination logic:</p><pre>useEffect(() =&gt; {<br>  if (!profile) return;<br>  (async () =&gt; {<br>  setIsLoading(true);<br>  // we&#39;ll call fetchRepos() here soon<br>  })();<br>}, [page]);</pre><p>Time to replace those placeholders with actual API calls.<br>Below the constants in Home.jsx, define the helper functions:</p><pre>const GH_API = &quot;https://api.github.com&quot;;<br><br>async function fetchProfile(username, headers) {<br>  const res = await fetch(`${GH_API}/users/${username}`, { headers });<br>  if (!res.ok) throw new Error(`User lookup failed (${res.status})`);<br>  return res.json();<br>}<br><br>async function fetchRepos(username, headers, page = 1) {<br>  const res = await fetch(<br>  `${GH_API}/users/${username}/repos?sort=updated&amp;per_page=10&amp;page=${page}`,<br>  { headers }<br>  );<br>  if (!res.ok) throw new Error(`Repo list failed (${res.status})`);<br>  return res.json();<br>}</pre><p>These functions:</p><ul><li>Handle all requests to GitHub’s public REST API</li><li>Throw descriptive errors if something goes wrong</li><li>Return parsed JSON so React can update its state cleanly</li></ul><h4>React Concepts at Work</h4><p>Let’s pause here and take a look at what’s happening under the hood.</p><p><strong>1. Asynchronous data fetching<br></strong> The <strong>fetchProfile</strong> and <strong>fetchRepos</strong> functions use <strong>async/await</strong> to call the GitHub API. In React, this pattern lets components handle real-time network data while keeping the UI responsive.</p><p>When a user searches for a profile, we await the results, and React continues rendering other parts of the page until the data arrives.</p><p><strong>2. Controlled re-rendering<br></strong> These functions don’t update the UI directly. Instead, they return JSON data that’s passed into React state setters like setProfile and setRepos.</p><p>Updating state triggers a re-render, and React can efficiently update only the components that depend on that data (e.g., ProfileCard or RepoList).</p><p><strong>3. Hooks for state and lifecycle<br></strong> The app uses <em>useState </em>to hold data (profile, repos, error, etc) and <em>useEffect</em> to watch for changes. In this case, useEffect runs the API calls whenever the current page number or username updates. This is how the app loads new repos automatically without a manual refresh.</p><p>Together, these features make React ideal for API-driven apps: data fetching, state changes, and UI updates all stay in sync with minimal boilerplate.</p><h4><strong>Why this project is not using a GitHub token (and why that’s okay)</strong></h4><p>You have probably noticed that this project is not using a GitHub API token, despite there being a place to input a token on our Search Form. GitHub’s REST API is open for <strong>public, read-only access</strong>. Anyone can fetch user profiles and repositories without authentication, which is just enough for small, quick client-side apps like this one.</p><p>When you call endpoints such as<br><strong> </strong><a href="https://api.github.com/users/%7Busername%7D"><strong>https://api.github.com/users/{username}</strong></a><br> or<br><strong> </strong><a href="https://api.github.com/users/%7Busername%7D/repos,"><strong>https://api.github.com/users/{username}/repos,</strong></a><br> GitHub automatically allows <strong>60 requests per hour per IP address,</strong> which is more than enough for our purposes. Using a <strong>personal access token</strong> raises the limit to<strong> 5,000 requests/hour.</strong></p><p>You can (and should!) look into using a <strong>personal access token </strong>in your next iteration of this application to gain experience with environment variables, but let’s get this up and running first.</p><h4><strong>State of the Union (aka Our Application)</strong></h4><p>Whew, okay! Your Home component is fully functional. Home can now officially:</p><ul><li>Manage all app state</li><li>Fetch GitHub profile and repos</li><li>Handle loading, pagination, and errors</li><li>Render everything dynamically with React hooks</li></ul><h3>Step 5: Create the Glassmorphic UI</h3><p>Time to make everything look pretty!</p><p><strong>Glassmorphism</strong> is a modern UI design style that mimics the look of <strong>frosted or translucent glass panels</strong> placed over a background.</p><p>Let’s level up our application by giving it a clean, frosted-glass panel floating on a gradient background:</p><pre>&lt;div className=&quot;flex justify-center items-start min-h-screen py-12 px-4&quot;&gt;<br>  &lt;div className=&quot;w-full max-w-4xl rounded-2xl bg-white/30 backdrop-blur-md shadow-2xl p-8 text-gray-900&quot;&gt;<br>    {/* app content here */}<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>The key utilities here are:</p><ul><li><strong>bg-white/30: </strong>translucent background</li><li><strong>backdrop-blur-md: </strong>the glass blur</li><li><strong>shadow-2xl: </strong>soft elevation shadow</li></ul><h3>Step 6: Animate the Background</h3><p>Let’s get a little extra — why not, we’ve come this far!</p><p>In <strong>App.jsx</strong>, add the gradient background:</p><pre>&lt;main className=&quot;min-h-screen bg-gradient-to-br from-purple-200 via-purple-500 to-indigo-800 text-gray-50 animate-gradient bg-[length:400%_400%]&quot;&gt;<br>  &lt;Home /&gt;<br>&lt;/main&gt;</pre><p>Next, extend Tailwind’s config to define the animation:</p><pre>keyframes: {<br>gradient: {<br>&quot;0%, 100%&quot;: { backgroundPosition: &quot;0% 50%&quot; },<br>&quot;50%&quot;: { backgroundPosition: &quot;100% 50%&quot; },<br>},<br>},<br>animation: {<br>gradient: &quot;gradient 15s ease infinite&quot;,<br>},<br>}</pre><p>The result is a soft, slowly moving gradient that gives the entire app a sense of depth and energy. Stunning!</p><h3>Step 7: Deploy</h3><p>Now that everything is working and looking lovely, it’s time to deploy your app to <strong>Vercel</strong>:</p><ol><li>Push your project to GitHub</li><li>Visit <strong>vercel.com/new</strong></li><li>Import your repository and click <strong>Deploy</strong></li></ol><p>Ta da! Your app will be live on a free .vercel.app domain within seconds</p><h3>But Wait, I’m Not Finished Yet!</h3><p>Here are just a few ideas if you’d like to continue iterating on this project:</p><ol><li><strong>Add dark mode:<br></strong> Use Tailwind’s dark: variant to support both light and dark themes.</li></ol><p><strong>2. Improve UX:<br></strong> Show rate-limit info (/rate_limit endpoint) or paginate repositories.</p><p><strong>3. Add a secret:<br></strong> Create a personal access token for the GitHub API and use it in a .env file at your project root. This will also unlock additional data from the API (e.g., private repos).</p><p><strong>4. Enhance data:<br></strong> Use the GitHub GraphQL API to display top languages and stars.</p><p><strong>5. Improve performance:<br></strong> Cache API responses in localStorage.</p><p><strong>6. Scale architecture:<br></strong> Add React Router for multiple pages like /user/:username.</p><p><strong>7. Tooling:<br></strong> Add Prettier + Husky for automated code formatting.</p><p><strong>8. Deployment:<br></strong> Set up a custom domain and GitHub Actions CI/CD pipeline.</p><p>The sky is the limit — happy coding!</p><h3>About the Author</h3><p><strong>Lexi</strong> has been working as a software developer since she switched careers into tech in 2019, and now holds a senior position at an engineering firm. Outside of work, she enjoys running, watching old horror movies, and spending time with her husband and one-year-old child.</p><p>You can connect with <strong>Lexi</strong> on <a href="https://www.linkedin.com/in/lexiantar/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e89d98e52d40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Simple Counter: Your First Step to Understanding React Hooks]]></title>
            <link>https://medium.com/@frontendqueens/the-simple-counter-your-first-step-to-understanding-react-hooks-a3b2abdda950?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3b2abdda950</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 13:02:06 GMT</pubDate>
            <atom:updated>2025-10-07T13:02:06.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="banner" src="https://cdn-images-1.medium.com/max/680/1*nsjLplnA_HuaPMlAab-hQw.png" /></figure><p>A simple counter is one of the most basic and beginner-friendly apps you can build in React. It showcases some of React’s core concepts, such as the <strong>useState</strong> hook and <strong>props</strong>. The goal of this article is to explore state management with the <strong>useState</strong> hook and data/function passing via <strong>props</strong>. In this example, of creating a Counter App, we will have three buttons — to <strong><em>increment</em></strong>, <strong><em>decrement</em></strong>, and <strong><em>reset</em></strong> — as well as to display the current count at any point of the operation.</p><p>Link of Live Project: <a href="https://deeptijnair.github.io/counter/">https://deeptijnair.github.io/counter/</a></p><p>Link of GitHub Repository: <a href="https://github.com/deeptijnair/counter">https://github.com/deeptijnair/counter</a></p><figure><img alt="image of the counter" src="https://cdn-images-1.medium.com/max/497/1*2Hume7g6rNz1EBGMglXPoA.png" /></figure><h3>Setting up your project</h3><p>Create a React application using the following command:</p><pre>npx create-react-app counter</pre><ul><li>Once the package and dependencies are installed and the counter app has been created, navigate to the newly created counter app.</li></ul><pre>cd counter</pre><ul><li>Install dependencies</li></ul><pre>npm install</pre><ul><li>Start the development server</li></ul><pre>npm start</pre><p>In the <strong><em>src</em></strong><em> </em>folder, create the following files.</p><p><strong>counter.js</strong> — A child component that will receive the count and functions as props, and creates the UI.</p><p><strong>styles.css</strong> — To add basic styling to our app and the counter</p><h3>Working of the Application</h3><p>The main components in this app are <strong>App.js</strong> and <strong>Counter.js</strong>. The components are separated to demonstrate the use of props and to show how the state can be handled in the parent while the UI logic is created in the child component.</p><p><strong>App.js</strong> is the parent component that holds the state. The <strong>useState</strong> hook in <strong>App.js</strong> manages the counter value and updates the counter state as needed.</p><pre>const [count, setCount] = useState(0);</pre><p>The handlers/functions for <strong><em>incrementing, decrementing, and resetting the counter</em></strong>, which actually modify the state, are also defined in <strong>App.js</strong>.</p><pre> const increment = () =&gt; setCount(count + 1);<br> const decrement = () =&gt; setCount(count - 1);<br> const reset = () =&gt; setCount(0);</pre><p>Props are passed down from the parent component (App.js) to the child component (Counter). These props include the current count and the handler functions created in the parent component.</p><pre>&lt;Counter<br>   count={count}<br>   increment={increment}<br>   decrement={decrement}<br>   reset={reset}<br>/&gt;</pre><p>Make sure to import the Counter component in the App.js before using it in the parent component.</p><pre>import Counter from &quot;./Counter&quot;;</pre><p>The <strong>Counter</strong> component is the child component and is responsible for displaying the count and handling the click operations on the buttons in the UI. It calls the relevant functions defined in the parent component, which are passed as a reference to the child using the prop whenever a button is clicked. These functions update the state in the parent, and the <strong>Counter</strong> then renders the updated value.</p><pre>  &lt;div className=&quot;counter&quot;&gt;<br>      &lt;h2&gt;{count}&lt;/h2&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={decrement}&gt;Decrement&lt;/button&gt;<br>      &lt;button onClick={reset}&gt;Reset&lt;/button&gt;<br>    &lt;/div&gt;</pre><p>This way, we have created a clean, light child component which can be easily modified as and when needed.</p><p>The handlers can be reused in other child components as well and need no duplication.</p><h3>Styling</h3><p>Finally, we can add some styling to improve the appearance of the app.</p><pre>html, body {<br>    height: 100%;<br>    margin: 0;<br>    display: flex;<br>    justify-content: center;<br>    align-items: center;<br>}<br><br>h1 {<br>    text-align: center;<br>}<br><br>h2 {<br>    font-size: 48px;<br>    margin: 20px;<br>    text-align: center;<br>}<br><br>.counter {<br>    border: 2px solid #000000;<br>    border-radius: 10px;<br>    align-items: center;<br>    padding: 20px;<br>}<br><br>button {<br>    background-color: #0b046a;<br>    color: white;<br>    border: none;<br>    border-radius: 5px;<br>    margin: 5px;<br>    padding: 10px 15px;<br>    font-size: 16px;<br>}</pre><h3>Conclusion</h3><p>In this article, we learned about two core concepts in React: state management using the <strong>useState</strong> hook and passing functions via props. Although the app is simple, the concepts covered here can be applied to building more advanced applications, such as to-do lists, calculators, and timers. As a next step, try modifying the counter to increment or decrement in steps of 5 or 10 instead of 1.</p><p>For this you can add another state that holds the step, and the default value can be set to 1.</p><h3>About the Author</h3><p><strong>Deepthi Nair </strong>is a passionate React and Next.js developer interning remotely. She loves building clean, user-friendly web apps and continuously learn new tools and technologies. Excited to grow, collaborate, and contribute to meaningful projects.</p><p>You can connect with <strong>Deepthi</strong> on <a href="http://www.linkedin.com/in/deepthijnair">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b2abdda950" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Weather App in React: A Beginner’s Guide]]></title>
            <link>https://medium.com/@frontendqueens/building-a-weather-app-in-react-a-beginners-guide-054c43251d40?source=rss-ef449ac5cfbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/054c43251d40</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[weather]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Frontend Queens]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 13:02:07 GMT</pubDate>
            <atom:updated>2025-10-01T07:12:48.734Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="banner" src="https://cdn-images-1.medium.com/max/680/1*BdvHLUQOw27s2iPgHacjfA.png" /></figure><p>Ah, the classic weather app. If you Google “Build a weather app”, you’ll come across hundreds — maybe thousands — of tutorials and guides. That’s because weather apps (along with to-do apps) have become a rite of passage for anyone learning React. They’re the bread and butter of the beginner React journey. And for good reason: a weather app is the perfect beginner project because it touches on key React concepts such as forms, state management, and fetching data from an API, all while being a fun and interesting project to work on.</p><p>In this guide, we’ll build a classic weather app together, breaking it down step by step. While this tutorial focuses on functionality rather than styling, you can check out the GitHub repo for some starter CSS to get you going. Feel free to customize it and make it your own. Most importantly, have fun with it!</p><p>Link of Live Project: <a href="https://weather-app-react-xi-ten.vercel.app/">https://weather-app-react-xi-ten.vercel.app/</a></p><p>Link of GitHub Repository: <a href="https://github.com/SarahSoutoul/weather-app-react">https://github.com/SarahSoutoul/weather-app-react</a></p><h3>Before we build</h3><h4>Prerequisites</h4><p>Before getting started, make sure you have the following installed on your computer:</p><ul><li>Node.js and NPM (Node Package Manager)</li><li>An IDE of your choice, such as Visual Studio Code</li></ul><h4>How the app works</h4><p>Here’s a quick overview of what the user interface will do:</p><ul><li>Users are presented with a form, where they can enter a city name.</li><li>After submission of the form, the app will display live weather data for that city.</li><li>The displayed information includes temperature, wind speed, humidity, and a brief description of the weather.</li></ul><h4>Tech used</h4><p>This weather app is built using:</p><ul><li><a href="https://vite.dev/">Vite</a> — a fast frontend build tool.</li><li><a href="https://react.dev/">React</a> — for building the user interface.</li><li><a href="https://www.google.com/search?q=open+weather+map&amp;rlz=1C5CHFA_enMX1132MX1132&amp;oq=open+weather+map&amp;gs_lcrp=EgZjaHJvbWUyCQgAEEUYORiABDIHCAEQABiABDIJCAIQABgKGIAEMgcIAxAAGIAEMgcIBBAAGIAEMgcIBRAAGIAEMgcIBhAAGIAEMgYIBxBFGDzSAQg2MzA2ajBqNKgCALACAA&amp;sourceid=chrome&amp;ie=UTF-8">OpenWeatherMap API</a> — to fetch live weather data.</li></ul><p>For this project to work, we will need to access some live weather data. There are several weather APIs out there, but for this guide, we will be using OpenWeatherMap. Make sure to sign up for a free account to access an API key — you’ll need it to fetch weather data.</p><h4>Setting up your project</h4><p>And, we are ready to go! To build our React project, we’ll be using <a href="https://vite.dev/">Vite</a>. Vite is a frontend build tool that provides a fast development environment, making it quick and easy to get a new project up and running.</p><ul><li>Open your terminal and create a new React + Vite application using the following command. Select <strong>React</strong> and <strong>JavaScript</strong> when prompted:</li></ul><pre>npm create vite@latest weather-app</pre><ul><li>This command will create a new React + Vite application in a folder named weather-app. Navigate into the project folder:</li></ul><pre>cd weather-app<br></pre><ul><li>Install dependencies</li></ul><pre>npm install</pre><ul><li>Start the development server</li></ul><pre>npm run dev</pre><p>This will spin up a local server (usually on <a href="http://localhost:5173/">http://localhost:5173</a>) where you can see your app running.</p><h4>Accessing the OpenWeatherMap API</h4><p>Before we can continue building this app, we need to make sure we have access to live weather data. As previously stated, we’ll be using OpenWeatherMap.</p><p>To successfully fetch data from this API, you will need an API key. Once you have signed up for a free account, navigate to the <strong>API Keys</strong> section in your dashboard.</p><p>Copy your active API key and save it somewhere safe — you’ll need it for your app.</p><h4>App structure</h4><p>To keep things simple, our app has just <strong>two components</strong>:</p><ul><li>WeatherForm: Handles user input and triggers the API call</li><li>WeatherCard: Displays the weather results if available</li></ul><p>Both components are rendered inside the main App.jsx.</p><p>When building a React app, it’s best to adopt a component-driven development approach. This means creating your components first and then using them to build your pages, piece by piece. It’s often called a bottom-up approach because you start with small, reusable components and gradually build up to complete pages.</p><p>Now, let’s start building our components!</p><h3>Building the components</h3><p>First, let’s organize our project structure. Inside the src folder, create a new folder called components. This is where we’ll store all of our reusable components. Inside components, create a file named WeatherForm.jsx , which will contain a functional component that will fetch weather data based on user input.</p><h4>Creating the form</h4><p>The WeatherForm is a <strong>controlled form</strong>, meaning the input value is stored in React state and updates as the user types. When the user clicks <strong>Get Weather</strong>, the form calls fetchWeather() and then resets the input.</p><pre>export default function WeatherForm({ city, setCity, fetchWeather }) { <br>   function handleChange(e) {<br>        setCity(e.target.value);<br>   };<br><br>   function handleSubmit(e) {<br>        e.preventDefault();<br>        // Function that makes the API call to fetch the weather data<br>        fetchWeather();<br>        setCity(&quot;&quot;);<br>   }<br><br>  return (<br>    &lt;form className=&quot;weatherForm&quot; onSubmit={handleSubmit}&gt;<br>        &lt;input <br>         type=&quot;text&quot; <br>         placeholder=&quot;Enter city name&quot;<br>         onChange={handleChange}<br>         value={city} <br>       /&gt;<br>        &lt;button&gt;Get weather&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>There are three props in this code snippet that need to be defined:</p><ul><li>city and setCity: The input value is controlled by the state. city contains the current input while setCity allows us to update it.</li><li>fetchWeather: A function that makes a GET request to our weather API and fetches the data for us. This pattern keeps things really clean - WeatherForm doesn’t know anything about the API itself, it just calls the function passed from App.jsx.</li></ul><p>All of these are passed as props to the WeatherForm component, meaning they should be defined in the top-level component: App. Keeping the state at the top level makes it easy to share data with multiple components without worrying about deeply nested props.</p><p><strong>Updating </strong><strong>App.jsx</strong></p><p>Navigate to the App.jsx file, and apply the following changes:</p><ul><li>Import the useState hook.</li><li>Create a new state using the useState hook.</li><li>Import WeatherForm at the top of the file.</li><li>Render WeatherForm and pass city , setCity as props.</li><li>Create the bare bones of the fetchWeather function, and pass it as a prop to the WeatherForm component.</li></ul><pre>import { useState } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import WeatherForm from &#39;./components/WeatherForm&#39;;<br><br>function App() {<br>  const [city, setCity] = useState(&quot;&quot;);<br> <br> const fetchWeather = async () =&gt; {<br>    const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;appid=${import.meta.env.VITE_APP_API_KEY}&amp;units=metric`);<br>    const data = await response.json();<br>    console.log(data)<br>  }<br>  <br>  return (<br>   &lt;div className=&#39;App&#39;&gt;<br>      &lt;WeatherForm city={city} setCity={setCity} fetchWeather={fetchWeather}/&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>Setting up your API key</strong></p><p>Let’s break down our fetchWeather function. As you may notice, the endpoint we’re fetching from takes the user-entered city and the API key we saved earlier as parameters.</p><p>Vite automatically loads environment variables starting withVITE_, so you can safely access it using import.meta.env.VITE_APP_API_KEY. Create a .env file in the root directory of your project, and add the following line to the file, replacing API_KEY with your actual API key:</p><pre>VITE_APP_API_KEY=API_KEY</pre><p><strong>Storing the weather data</strong></p><p>So what’s left to do? Currently, we are just printing our data to the console, but what we really want is to store it in a piece of state (for e.g., weatherData) so we can then display it on the screen.</p><p>Here is the new App.jsx with the addition of a weatherData state:</p><pre>import { useState } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import WeatherForm from &#39;./components/WeatherForm&#39;;<br><br>function App() {<br>  const [city, setCity] = useState(&quot;&quot;);<br> const [weatherData, setWeatherData] = useState(null);<br> <br> const fetchWeather = async () =&gt; {<br>    const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;appid=${import.meta.env.VITE_APP_API_KEY}&amp;units=metric`);<br>    const data = await response.json();<br>   setWeatherData(data)<br>  }<br>  <br>  return (<br>   &lt;div className=&#39;App&#39;&gt;<br>      &lt;WeatherForm city={city} setCity={setCity} fetchWeather={fetchWeather}/&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>Testing</strong></p><p>Once this is done, navigate to <a href="http://localhost:5173/">http://localhost:5173/</a> and you should be able to do the following to test the code:</p><ul><li>Enter a city (e.g., London) in the input field and submit your entry by clicking on the button</li><li>Once your entry is submitted, the weatherData should contain the weather data for your entered city. To check this, I would recommend using the <a href="https://chromewebstore.google.com/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en&amp;pli=1">React DevTools Google Chrome extension</a>. This extension will allow you to inspect the contents of weatherData - see an example below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kqI4F3KqjYUB61CI" /></figure><h3>WeatherCard</h3><p>Yayy, we have our data. Now, it is time to display it on the screen.</p><p>Create a new file in the components folder called WeatherCard.jsx . This component will receive weatherData as a prop and display it nicely. Here’s the code:</p><pre>import {useState} from &#39;react&#39;;<br><br>const options = {<br>  weekday: &quot;long&quot;,<br>  day: &quot;numeric&quot;,<br>  month: &quot;long&quot;,<br>  year: &quot;numeric&quot;<br>};<br><br>export default function WeatherCard({ weatherData }) {<br>  const [isCelsius, setIsCelsius] = useState(true);<br><br>  const toggleTemperature = () =&gt; {<br>    setIsCelsius(!isCelsius);<br>  }<br><br>  const renderTemperature = (temperature) =&gt; {<br>    if(isCelsius) {<br>      // convert in celsius<br>      return Math.round(temperature);<br>    } else {<br>      // convert in F<br>      return Math.round((temperature * 9) / 5 + 32);<br>    }<br>  }<br><br>  return (<br>    &lt;&gt;<br>      {weatherData &amp;&amp; (<br>        &lt;&gt;<br>          &lt;h2 className=&#39;city&#39;&gt;{weatherData.name}&lt;/h2&gt;<br>          &lt;p className=&quot;date&quot;&gt;{new Date(weatherData.dt * 1000).toLocaleDateString(&quot;en-US&quot;, options)}&lt;/p&gt;<br>          &lt;div className=&quot;temperature&quot;&gt;<br>            {renderTemperature(weatherData.main.temp)}<br>            &lt;sup className=&#39;temp-unit&#39; onClick={toggleTemperature}&gt;<br>              {isCelsius ? &quot;°C&quot; : &quot;°F&quot;} | {isCelsius ? &quot;°F&quot; : &quot;°C&quot;}<br>            &lt;/sup&gt;<br>          &lt;/div&gt;<br>          &lt;p className=&#39;description&#39;&gt;{weatherData.weather[0].description.toUpperCase()}&lt;/p&gt;<br>          &lt;div className=&#39;weather-details&#39;&gt;<br>            &lt;div className=&#39;col&#39;&gt;<br>              &lt;div&gt;<br>                &lt;p&gt;{weatherData.wind.speed} m/s&lt;/p&gt;<br>                &lt;p&gt;Wind speed&lt;/p&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&#39;col&#39;&gt;<br>              &lt;div&gt;<br>                &lt;p&gt;{weatherData.main.humidity} %&lt;/p&gt;<br>                &lt;p&gt;Humidity&lt;/p&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/&gt;<br>  );<br>}</pre><p>Let’s break down what’s happening in this component:</p><ul><li>If weatherData is not null, we display the weather information returned from the API.</li><li>We convert the timestamp from the API into a readable format using new Date() and toLocaleDateString().</li><li>Temperature toggle: Users can switch between Celsius and Fahrenheit:</li><li>renderTemperature() converts the temperature based on the isCelsius state.</li><li>toggleTemperature() switches the temperature unit when the user clicks the unit.</li></ul><p><strong>Using </strong><strong>WeatherCard in </strong><strong>App.jsx</strong></p><p>Let’s add this component to App.jsx. Navigate to the App.jsx file, and apply the following changes:</p><ul><li>Import the WeatherCard at the top of the file.</li><li>Render WeatherCard and pass weatherData as a prop.</li></ul><pre>import { useState } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import WeatherForm from &#39;./components/WeatherForm&#39;;<br>import WeatherCard from &#39;./components/WeatherCard&#39;;<br><br>function App() {<br>  const [city, setCity] = useState(&quot;&quot;);<br> const [weatherData, setWeatherData] = useState(null);<br> <br> const fetchWeather = async () =&gt; {<br>    const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;appid=${import.meta.env.VITE_APP_API_KEY}&amp;units=metric`);<br>    const data = await response.json();<br>   setWeatherData(data);<br>  };<br>  <br>  return (<br>   &lt;div className=&#39;App&#39;&gt;<br>      &lt;WeatherForm <br>       city={city} <br>       setCity={setCity} <br>       fetchWeather={fetchWeather}<br>     /&gt;<br>      &lt;WeatherCard weatherData={weatherData} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>Testing</strong></p><p>It’s time to test our code! Make sure your dev server is running, and navigate to <a href="http://localhost:5173/">http://localhost:5173/</a> in your browser. You should be able to go through the same process of entering a city name and clicking the button, but this time, the weather data should appear on the screen.</p><p>Congrats, you React queen/ king 🎉 You have successfully built a React application that fetches weather data based on user input, and displays that data on the screen. Now, the world is your oyster, and there is so much more you can add to this app.</p><h3>Possible improvements/ additions</h3><ul><li>When a user first loads the app, there could be some initial data loaded for a default city. <strong>Hint: you should use </strong><strong>useEffect for this to work.</strong></li><li>You could dive deeper into the weather API and see what other data can be fetched/ displayed. For example, there is an endpoint that allows you to get a five-day forecast. Pretty cool, eh?</li><li>You could add some fun animation, such as a loading spinner, while the data is being fetched.</li><li>You could display some fun icons — for example, if the weather predicts “rain”, you could have a rain emoji.</li><li>Finally, add some styling and have fun with it!</li></ul><p>Happy coding!</p><h3>About the Author</h3><p><em>Sarah Soutoul is a France-born professional with a background in software engineering and tech education. After three years as a software engineer in the media publishing industry, she transitioned into technology training and curriculum development, helping individuals navigate their own tech journeys.</em></p><p><em>Inspired by the mentorship she received early in her own journey, Sarah is committed to creating empowering spaces for women, encouraging them to pursue careers in tech and see themselves as future tech leaders.</em></p><p>You can connect with <strong>Sarah</strong> on<a href="https://www.linkedin.com/in/sarah-soutoul-4a422a139/"> LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=054c43251d40" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>