<?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 Juvita Saini on Medium]]></title>
        <description><![CDATA[Stories by Juvita Saini on Medium]]></description>
        <link>https://medium.com/@juvitasaini?source=rss-6c971dc4f924------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*af-FtieockyF45yr</url>
            <title>Stories by Juvita Saini on Medium</title>
            <link>https://medium.com/@juvitasaini?source=rss-6c971dc4f924------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 18 May 2026 06:31:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juvitasaini/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[ How to Avoid Prisma Migration Issues — A Simple Team Workflow Guide]]></title>
            <link>https://medium.com/@juvitasaini/how-to-avoid-prisma-migration-issues-a-simple-team-workflow-guide-79fe5911c64e?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/79fe5911c64e</guid>
            <category><![CDATA[prisma-orm]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[orm]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 16:50:17 GMT</pubDate>
            <atom:updated>2025-12-08T16:50:17.752Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 How to Avoid Prisma Migration Issues — A Simple Team Workflow Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*YheucFpkrqQtXvdUyjP80g.png" /></figure><p>Working with <strong>Prisma</strong> in a team is amazing… <em>until</em> migrations start breaking everything.<br> If you’ve ever faced weird schema errors, missing migration files, or “schema drift detected” warnings, you’re not alone. 😅</p><p>👉 <strong>Most issues happen because migration files and local databases are not in sync.</strong></p><p>So here is a clean and consistent workflow your whole team can follow to avoid Prisma headaches.</p><h3>🧱 1. Making Changes to schema.prisma</h3><p>When you update the schema, keep these rules in mind:</p><h3>✅ Do this:</h3><ul><li><strong>Always generate a migration</strong> whenever you change the schema.</li><li><strong>Pull the latest code</strong> before generating any new migration.</li><li><strong>Keep migration files safe</strong> — don’t delete migrations created by teammates.</li><li><strong>Use clear naming conventions</strong> (just like git commit messages)</li></ul><p>Example:</p><pre>npx prisma migrate dev --name &quot;add_user_table&quot;</pre><h3>❌ Don’t do this:</h3><ul><li>Don’t run prisma migrate reset casually.</li><li>Don’t skip migration generation.</li><li>Don’t override schema changes by others.</li><li>Don’t delete a migration file to “fix” something.</li></ul><h3>🔍 If you see a migration in DB but not in folder</h3><p>Example:<br> 20251204065339_test_model appears in your DB but not in /prisma/migrations</p><p>This means:<br> ➡️ Someone created a migration locally but didn’t commit it<br> OR<br> ➡️ You deleted a migration file accidentally</p><p><strong>How to fix:</strong></p><ol><li>git pull origin main</li><li>If file is still missing, ask the teammate who created it</li><li>Never delete migration files manually</li></ol><h3>🔄 2. Daily Pull Is Mandatory</h3><p>Before you write <strong>even one line of code</strong>, do a daily pull.<br> It prevents 90% of migration mismatches.</p><h3>Daily starting checklist:</h3><pre># 1. Pull latest changes<br>git pull origin main</pre><pre># 2. Apply new migrations<br>npx prisma migrate dev</pre><p>This ensures:</p><ul><li>Your schema is fully updated</li><li>Your local DB matches the team’s version</li><li>You don’t accidentally override someone else’s work</li></ul><h3>🛠️ Generating New Migrations Properly</h3><p>Whenever you modify schema.prisma, generate a migration <strong>with a clear name</strong>:</p><pre>npx prisma migrate dev --name &quot;add_user_email_field&quot;</pre><p>Some good examples:</p><ul><li>add_user_table</li><li>add_email_to_users</li><li>remove_legacy_posts_table</li><li>update_payment_model</li></ul><p>Your future self will thank you. 😄</p><h3>🐛 Troubleshooting Common Issues</h3><h3>❗️“Migration file exists in database but not in prisma/migrations folder”</h3><p><strong>Cause:</strong><br> A teammate didn’t commit their migration OR you deleted a migration.</p><p><strong>Fix:</strong></p><ul><li>Pull latest</li><li>Ask the teammate who created it</li><li>Commit missing migrations</li><li>Never delete migrations yourself</li></ul><h3>❗️“Schema drift detected”</h3><p><strong>Cause:</strong><br> Your local database and migration history don’t match.</p><p><strong>Fix:</strong><br> Follow the daily workflow + avoid resets.</p><h3>📌 Quick Reference (Do vs Don’t)</h3><h3>✅ Do:</h3><ul><li>Pull before editing the schema</li><li>Generate migrations for every change</li><li>Use descriptive migration names</li><li>Commit migrations</li><li>Pull daily before work</li></ul><h3>❌ Don’t:</h3><ul><li>Don’t use migrate reset carelessly</li><li>Don’t delete migrations</li><li>Don’t push schema changes without migrations</li><li>Don’t work on an outdated schema</li></ul><h3>🎯 Final Thoughts</h3><p>Prisma is powerful, but it requires discipline when working in a team.<br> Following this simple workflow will save everyone hours of debugging — and keep your project clean, stable, and stress-free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79fe5911c64e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Throwing Errors in Next.js Server Actions (Well… Sometimes)]]></title>
            <link>https://medium.com/@juvitasaini/stop-throwing-errors-in-next-js-server-actions-well-sometimes-e3cfd9ef9fdb?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3cfd9ef9fdb</guid>
            <category><![CDATA[nextjs-server-action]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[json-serialization]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[error]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 07:32:56 GMT</pubDate>
            <atom:updated>2025-11-13T07:32:56.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FJ0MJuc6TIjSd5SOpbmPg.png" /></figure><p>We all love a good throw new Error(), right? But in <strong>Next.js server actions</strong>, that innocent line can sometimes become a silent troublemaker — especially in production!</p><h3>😬 The Problem</h3><p>When you do this:</p><pre>throw new Error(&#39;Something went wrong&#39;) // ❌ Bad</pre><p>you might notice… sometimes the error just disappears.<br> No message. No clue. Nothing. 🤷‍♀️</p><p>Here’s why:<br> When your server sends something to the browser, <strong>Next.js needs to convert it into plain text or JSON</strong> so it can travel through the network.</p><p>That conversion is called <em>serialization</em>.</p><p>But…. JavaScript Error objects have a bunch of hidden technical info inside (like stack traces and internal links) — and those parts <strong>can’t be converted properly</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXcUepInltNaPMhKfn86Gw.png" /></figure><p>So when Next.js tries to send the error to the client, it basically goes:</p><blockquote><em>“Oops, I don’t know how to send this thing… I’ll just skip it.”</em></blockquote><p>And that’s how your error details vanish into thin air 💨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSWLql8ptF07XqO7XLmRMA.png" /></figure><h3>💡 The Better Way</h3><p>Instead of throwing, <strong>return a simple object</strong> that you can safely send and display:</p><pre>try {<br>  const user = await getUser()<br>  return { success: true, data: user }<br>} catch (error) {<br>  return {<br>    success: false,<br>    error: error instanceof Error ? error.message : &#39;Something went wrong&#39;,<br>  }<br>}</pre><p>This way, you:</p><ul><li>Keep full control of what reaches the UI</li><li>Always get readable messages</li><li>Avoid those mysterious “nothing happened” errors</li></ul><h3>🚨 When Throwing Is Okay</h3><p>Sometimes you <em>should</em> throw — like when your app can’t continue:</p><pre>// Example 1: Config is missing<br>if (!process.env.DATABASE_URL) {<br>  throw new Error(&#39;Database not configured&#39;)<br>}</pre><pre>// Example 2: Unauthorized user<br>if (!isAuthorized) {<br>  throw new Error(&#39;Unauthorized&#39;)<br>}</pre><p>Throwing makes sense when something is <strong>fundamentally broken</strong>, not just when something <em>went wrong</em>.</p><h3>💭 TL;DR</h3><p>SituationWhat to DoRegular app or API error✅ Return { success, error }Critical crash (should stop everything)💥 Throw an error</p><h3>🌸 Wrap-Up</h3><p>So yeah, in Next.js server actions — <br> <strong>Throw only when you want a crash, not when you want clarity.</strong><br> Returning clean objects keeps your UI happy and your users even happier 💖</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3cfd9ef9fdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding CSR, SSR, SSG & ISR — The Magical Rendering Styles of Web Wonderland ‍♀️]]></title>
            <link>https://medium.com/@juvitasaini/understanding-csr-ssr-ssg-isr-the-magical-rendering-styles-of-web-wonderland-%EF%B8%8F-a3f8845d7534?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3f8845d7534</guid>
            <category><![CDATA[csr]]></category>
            <category><![CDATA[ssrs]]></category>
            <category><![CDATA[ssg]]></category>
            <category><![CDATA[isr]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 15:06:51 GMT</pubDate>
            <atom:updated>2025-07-27T15:06:51.382Z</atom:updated>
            <content:encoded><![CDATA[<h3>🌈 Understanding CSR, SSR, SSG &amp; ISR — The Magical Rendering Styles of Web Wonderland 🧙‍♀️</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nLRUA620kS-UDK-dr55HA.png" /></figure><blockquote><em>Ever wondered how your favorite websites load so fast, feel super interactive, or show up perfectly on Google Search? 🤔</em></blockquote><blockquote><em>Welcome to the enchanted world of </em><strong><em>modern web rendering techniques</em></strong><em> — where four little acronyms make a </em>big<em> difference: </em><strong><em>CSR, SSR, SSG, and ISR</em></strong><em>.</em></blockquote><blockquote><em>Let’s break them down in a fun, storybook-style guide you’ll love reading 💖</em></blockquote><h3>🧁 Once Upon a Web: The Old School Days</h3><p>Before React, Vue, or Next.js, developers used tools like <strong>PHP</strong> to generate web pages. Each time you visited a page, the server would:</p><p>🖥️ Fetch data<br> 🧠 Process logic<br> 🧾 Inject content into HTML<br> 🚀 Send full page to your browser</p><p>That was cool back then… but as websites grew heavier (imagine loading Instagram or YouTube this way), problems started appearing:</p><ul><li>😵‍💫 High server load</li><li>🐢 Slow for users with poor internet</li><li>🔄 Full page reload on every click</li></ul><h3>💫 Enter the Heroes of Rendering! 💫</h3><h3>🌟 1. Client-Side Rendering (CSR) — The JavaScript Magician 🧙‍♂️</h3><p>In CSR, the server sends <strong>a blank HTML page with JavaScript files</strong>. Then your browser (client) magically builds the actual content using those scripts.</p><p>💡 Example: A React Single Page Application (SPA)</p><p><strong>Advantages:</strong></p><ul><li>✨ Super interactive</li><li>😌 Less load on server</li><li>🔁 Dynamic updates without reloads</li></ul><p><strong>Drawbacks:</strong></p><ul><li>🐌 Initial load can be slow</li><li>🙈 SEO suffers (Google bots can’t see client-rendered content)</li></ul><p><strong>Test it yourself</strong>:<br> Open DevTools → Network tab → Reload page.<br> Notice you get minimal HTML first, and the rest loads via JS.</p><h3>🌍 2. Server-Side Rendering (SSR) — The Chef Who Prepares Your Page 🍽️</h3><p>SSR means the <strong>server prepares the full HTML with content</strong> and sends it directly to the browser. The browser shows it instantly, even while JavaScript is still loading.</p><p>💡 Example: A Next.js app using getServerSideProps</p><p><strong>Advantages:</strong></p><ul><li>⚡ Fast first load</li><li>🔍 Better SEO (bots see real content)</li><li>✅ Great for dynamic content (like dashboards, profile pages)</li></ul><p><strong>Drawbacks:</strong></p><ul><li>😮‍💨 More load on server</li><li>🐢 Might be slower than static pages</li></ul><p><strong>Cute Tip</strong>: Try viewing page source of an SSR page — you’ll see real content! Now turn off JavaScript and click around — it won’t work. That’s hydration missing.</p><h3>📦 3. Static Site Generation (SSG) — The Lazy Genius 🧘‍♀️</h3><p>SSG creates <strong>all HTML pages ahead of time</strong> (at build time). When someone visits the site, they get a pre-made page — it’s like taking cookies from the jar instead of baking them each time 🍪</p><p>💡 Example: A blog built with Next.js using getStaticProps</p><p><strong>Advantages:</strong></p><ul><li>🏎️ Ultra fast</li><li>🧵 Great for SEO</li><li>🧃 Simple, cache-friendly</li></ul><p><strong>Drawbacks:</strong></p><ul><li>📅 Can’t show fresh content instantly</li><li>🔄 Need to rebuild site for updates</li></ul><p><strong>Best for:</strong> Blogs, portfolios, marketing sites</p><h3>⏱️ 4. Incremental Static Regeneration (ISR) — The Smart Assistant 🤖</h3><p>ISR is like SSG… but smarter! 🧠 You don’t need to rebuild the <em>whole</em> site. Just update specific pages on demand or at time intervals.</p><p>💡 Example: Next.js revalidate option inside getStaticProps</p><p><strong>Advantages:</strong></p><ul><li>🔁 Keeps site fast</li><li>🛠️ Can update dynamic data (like prices or listings)</li><li>👌 Saves dev effort</li></ul><p><strong>Drawbacks:</strong></p><ul><li>⏳ Updates aren’t instant (depends on time or trigger)</li><li>🧪 Slightly more setup than basic SSG</li></ul><h3>🧭 When Should You Use What?</h3><p>TechniqueBest ForExample<strong>CSR</strong>Highly interactive SPAsSocial media apps<strong>SSR</strong>SEO + dynamic pagesE-commerce product page<strong>SSG</strong>Static contentBlog, docs, portfolio<strong>ISR</strong>Static + frequent updatesNews feed, job boards</p><h3>🎯 Final Thoughts: Choose Your Magic Wisely</h3><p>Each technique is like a <strong>superpower</strong> 💥 and the trick is knowing <em>when</em> to use what:</p><ul><li>Want lightning-fast pages? → Go SSG</li><li>Need fresh data on every load? → SSR</li><li>Care about interactivity? → CSR</li><li>Want speed + freshness? → ISR</li></ul><p>Next.js gives you <em>all</em> these options under one cozy roof 🏠, and that’s what makes it the most loved framework right now 💙</p><h3>☁️ Bonus: Cute Analogy Corner ☁️</h3><p>ModeAnalogyCSR🍲 Instant noodles you cook in your own kitchenSSR🍽️ Restaurant where chef serves hot foodSSG🍪 Pre-packed snack ready to eatISR🍰 Snack that auto-restocks in the fridge every few hours</p><h3>💌 Stay Curious &amp; Keep Coding</h3><p>This world of web development is <strong>super exciting</strong>, and there’s <em>always</em> something new to learn.</p><p>Until next time — Happy Building &amp; Stay Awesome! 💻🌼</p><p><strong>👩‍💻 Written by Juvita Saini</strong><br> Frontend Dev | Tech Storyteller | Lifelong Learner</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3f8845d7534" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Set vs Map in JavaScript — A Cozy Little Guide]]></title>
            <link>https://medium.com/@juvitasaini/set-vs-map-in-javascript-a-cozy-little-guide-b323f0b70506?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/b323f0b70506</guid>
            <category><![CDATA[javascript-set-vs-map]]></category>
            <category><![CDATA[frontend-interview-prep]]></category>
            <category><![CDATA[set]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[beginner-javascript-guide]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 20:13:40 GMT</pubDate>
            <atom:updated>2025-06-22T20:37:17.696Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧡 Set vs Map in JavaScript — A Cozy Little Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEGwzEV1g9OHJbxH5U5Xcw.png" /></figure><p>Ever felt like JavaScript has too many data structures to keep up with?<br> You’re not alone. Let’s talk about two superstars today: Set and Map. But don’t worry — this won’t feel like school.</p><h3>🧺 What is a Set?</h3><p>Think of a Set as a basket 🧺 — but it <strong>only allows unique items</strong>.</p><pre>const basket = new Set();<br>basket.add(&quot;apple&quot;);<br>basket.add(&quot;banana&quot;);<br>basket.add(&quot;apple&quot;);  // duplicate!<br>console.log(basket);  // Set(2) { &quot;apple&quot;, &quot;banana&quot; }</pre><p><strong>Key Idea</strong>:</p><blockquote><em>Sets store only </em><strong><em>unique values</em></strong><em>.<br> No duplicates. Just clean, fresh items.</em></blockquote><h3>🔐 What is a Map?</h3><p>Now think of a Map as a <strong>locker with key-value pairs</strong> 🔐</p><pre>const locker = new Map();<br>locker.set(&quot;name&quot;, &quot;Juvita&quot;);<br>locker.set(&quot;job&quot;, &quot;Frontend Developer&quot;);<br>locker.set(&quot;name&quot;, &quot;Awesome Juvita&quot;); // keys are unique!<br>console.log(locker); // {&#39;name&#39; =&gt; &#39;Awesome Juvita&#39;, &#39;job&#39; =&gt; &#39;Frontend Developer&#39;}</pre><p><strong>Key Idea</strong>:</p><blockquote><em>Maps store data in </em><strong><em>key → value</em></strong><em> format.<br> And the keys? They can be </em><strong><em>anything</em></strong><em> — strings, numbers, even objects!</em></blockquote><h3>🧺 Set — The No-Duplicate Gang</h3><h4>🔑 Key Properties of Set:</h4><pre>------------------------------------------------------<br>| Property/Method  | What it does                    |<br>| ---------------- | ------------------------------- |<br>| new Set()        | Creates a new Set               |<br>| .add(value)      | Adds a value                    |<br>| .has(value)      | Checks if the value exists      |<br>| .delete(value)   | Removes a value                 |<br>| .size            | Tells how many items are inside |<br>| .clear()         | Empties the set completely      |<br>| Iterates with    | &#39;for...of&#39;, .forEach()          |<br>------------------------------------------------------</pre><p>✅ Code Example:</p><pre>const fruits = new Set();<br>fruits.add(&quot;apple&quot;);<br>fruits.add(&quot;banana&quot;);<br>fruits.add(&quot;apple&quot;); // ignored<br>console.log(fruits); // Set(2) { &quot;apple&quot;, &quot;banana&quot; }<br>console.log(fruits.has(&quot;banana&quot;)); // true<br>console.log(fruits.size); // 2<br>fruits.delete(&quot;apple&quot;);<br>console.log(fruits); // Set(1) { &quot;banana&quot; }<br><br>add-has-delete-size ( important properties )</pre><h4>🧰 Use Cases:</h4><ul><li>Removing duplicates from an array</li><li>Checking visited items (like visited pages)</li><li>Storing unique selections (like tags, filters)</li><li>Fast membership testing</li></ul><h3>🔐 Map — The Key-Value Power Couple</h3><h4>🔑 Key Properties of Map:</h4><pre>-----------------------------------------------------------------<br>| Property/Method    | What it does                             |<br>| ------------------ | ---------------------------------------- |<br>| new Map()          | Creates a new Map                        |<br>| .set(key, value)   | Adds or updates a value by key           |<br>| .get(key)          | Gets the value for a key                 |<br>| .has(key)          | Checks if the key exists                 |<br>| .delete(key)       | Deletes the key-value pair               |<br>| .size              | Number of pairs                          |<br>| .clear()           | Empties the map                          |<br>| Iterates with      | for...of, .forEach() on .entries()       |<br>-----------------------------------------------------------------</pre><h4>🧰 Use Cases:</h4><ul><li>Storing key-value pairs (like a phone book)</li><li>Caching results</li><li>Counting frequencies</li><li>Creating lookup tables (like for grouping anagrams!)</li></ul><p>✅ Code Example:</p><pre>const userInfo = new Map();<br><br>userInfo.set(&quot;name&quot;, &quot;Juvita&quot;);<br>userInfo.set(&quot;age&quot;, 24);<br>userInfo.set(&quot;isDeveloper&quot;, true);<br><br>console.log(userInfo.get(&quot;name&quot;)); // &quot;Juvita&quot;<br>console.log(userInfo.has(&quot;age&quot;));  // true<br>console.log(userInfo.size);        // 3<br><br>userInfo.delete(&quot;isDeveloper&quot;);<br>console.log(userInfo); // Map(2) { &quot;name&quot; =&gt; &quot;Juvita&quot;, &quot;age&quot; =&gt; 24 }<br><br>set-get-delete-size ( important properties )</pre><h3>🌈 When Should I Use What?</h3><ul><li>You want to <strong>store unique items only</strong></li><li>You want to <strong>check if something exists</strong> (like checking login tokens or visited pages)</li><li>You’re de-duping arrays</li></ul><pre>const nums = [1, 2, 2, 3, 3, 3];<br>const uniqueNums = [...new Set(nums)];<br>console.log(uniqueNums); // [1, 2, 3]</pre><h4>✅ Use a Map when:</h4><ul><li>You need to associate values with <strong>keys</strong></li><li>Your keys might be <strong>objects, arrays, functions</strong> (not just strings)</li><li>You care about <strong>insertion order</strong> and performance</li></ul><pre>const cart = new Map();<br>cart.set({ id: 1 }, &quot;Shirt&quot;);<br>cart.set({ id: 2 }, &quot;Jeans&quot;);<br>// keys are objects!</pre><h3>🧠 Quick Memory Trick:</h3><ul><li><strong>Set</strong> = Unique values only, like a clean plate 🍽️</li><li><strong>Map</strong> = A mini-dictionary 📖 (Key → Value)</li></ul><h3>💬 Real Talk</h3><p>✨ I personally use:</p><ul><li>Set when working with arrays I need to clean up.</li><li>Map when building logic-heavy things like:</li><li>Caching data,</li><li>Grouping items by categories,</li><li>Creating efficient lookups.</li></ul><p>They’re not scary. They’re just different kinds of helpers. 🤝</p><h3>🥰 Wrapping it with Love</h3><p>So next time you need to:</p><ul><li>Throw in a bunch of items without worrying about duplicates? 👉 Use Set.</li><li>Organize data like a dictionary with flexible keys? 👉 Use Map.</li></ul><p>Just remember:</p><blockquote><em>Set is your cool minimal bestie ✨<br> </em><em>Map is your super-organized brainy friend 🤓</em></blockquote><p>Now you’re ready to boss them around like a JS queen/king 👑</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b323f0b70506" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Effortless Authentication to React/Next.js with Clerk]]></title>
            <link>https://medium.com/@juvitasaini/add-effortless-authentication-to-react-next-js-with-clerk-68a676fdda73?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a676fdda73</guid>
            <category><![CDATA[clerk-auth]]></category>
            <category><![CDATA[clerks]]></category>
            <category><![CDATA[next-js-13]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 09:07:08 GMT</pubDate>
            <atom:updated>2025-06-06T10:46:44.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHh-WX6B9GyeeMvmqi_t1Q.png" /></figure><p>Let’s learn authentication with clerk</p><h4>✨ 1. Introduction</h4><blockquote><em>Authentication is one of the first features every app needs — and often one of the most annoying to build from scratch. Recently, I integrated </em><a href="https://clerk.com"><em>Clerk</em></a><em> into my project, and honestly, I was impressed by how quick and developer-friendly the setup process was.</em></blockquote><blockquote><em>In this blog, I’ll walk you through how to set up Clerk authentication in your React or Next.js project, so you can get started in minutes — no backend hassle — no reinventing the wheel.</em></blockquote><p>💡 One thing I really liked was how easy Clerk’s documentation is to understand. You can try following it first — but if you get stuck or want a clearer explanation, this blog will guide you step by step. Let’s get started!</p><h3>🔍 2. What is Clerk?</h3><blockquote><em>It handles sign-in, sign-up, user profiles, sessions, and even multi-factor authentication— all out of the box.</em></blockquote><blockquote><em>The beauty of Clerk is:<br> ✅ Fully managed — no backend setup needed<br> ✅ Pre-built UI components (SignIn, SignUp, UserButton)<br> ✅ Works with social logins, magic links, passwords<br> ✅ Great developer experience (DX)</em></blockquote><p>If you’re tired of manually building login forms or managing JWTs, Clerk is a breath of fresh air.</p><h3>⚙️ 3. Setting up Clerk in your Next.js app</h3><h4>🧩 Step 1: Install Clerk</h4><pre>npm install @clerk/nextjs</pre><h4>🔑 Step 2: clerkMiddleware(): Create a middleware.js file</h4><p><a href="https://clerk.com/docs/references/nextjs/clerk-middleware">clerkMiddleware()</a> grants you access to user authentication state throughout your app.</p><pre>import { clerkMiddleware } from &#39;@clerk/nextjs/server&#39;<br><br>export default clerkMiddleware()<br><br>export const config = {<br>  matcher: [<br>    // Skip Next.js internals and all static files, unless found in search params<br>    &#39;/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)&#39;,<br>    // Always run for API routes<br>    &#39;/(api|trpc)(.*)&#39;,<br>  ],<br>}</pre><h4>🧱 Step 3: Wrap your app in &lt;ClerkProvider&gt;</h4><pre><br>import {<br>  ClerkProvider,<br>} from &#39;@clerk/nextjs&#39;<br><br>export default function RootLayout({<br>  children,<br>}) {<br>  return (<br>    &lt;ClerkProvider&gt;<br>      &lt;html lang=&quot;en&quot;&gt;<br>        &lt;body &gt;<br>          {children}<br>        &lt;/body&gt;<br>      &lt;/html&gt;<br>    &lt;/ClerkProvider&gt;<br>  )<br>}</pre><h4>🧑‍💼 Step 4: Add Clerk UI Components to Your App (Header)</h4><p>Clerk gives you prebuilt React components that are super easy to plug into your layout. Let’s add a simple <strong>Header</strong> to your app that shows:</p><ul><li>A “Sign In” button when the user is not logged in</li><li>A “User Profile” button when the user is logged in</li></ul><pre>&quot;use client&quot;;<br><br>import {<br>  SignedIn,<br>  SignedOut,<br>  UserButton,<br>  SignInButton,<br>} from &quot;@clerk/nextjs&quot;;<br><br>export default function Header() {<br>  return (<br>    &lt;header className=&quot;flex justify-between mt-16&quot;&gt;<br>     <br>    {/* when user is not signed in */}<br>        &lt;SignedOut&gt;<br>          &lt;SignInButton /&gt;<br>        &lt;/SignedOut&gt;<br><br>     {/* when user is signed in */}<br>        &lt;SignedIn&gt;<br>   {\* afterSignOutUrl : it’s the redirect URL after signing out, <br>     which beginners might wonder about. */}<br>          &lt;UserButton afterSignOutUrl=&quot;/&quot; /&gt;<br>        &lt;/SignedIn&gt;<br>  <br>    &lt;/header&gt;<br>  );<br>}</pre><p>Now import this component in your layout.tsx file or wherever you manage layout across pages:</p><pre>import Header from &quot;@/components/Header&quot;;<br><br>export default function RootLayout({ children }) {<br>  return (<br>    &lt;ClerkProvider&gt;<br>      &lt;html lang=&quot;en&quot;&gt;<br>        &lt;body&gt;<br><br>       {/* Header that includes both &lt;SignedIn&gt; and &lt;SignedOut&gt; components*/}<br>          &lt;Header /&gt;<br><br>          {children}<br>        &lt;/body&gt;<br>      &lt;/html&gt;<br>    &lt;/ClerkProvider&gt;<br>  );<br>}</pre><p>Once this is done, your app now has <strong>basic authentication UI</strong> with zero custom code. 🎉</p><h3>🧪 How to Test Your Setup</h3><p>To test your app locally: Open your terminal</p><pre>npm run dev</pre><ol><li>Visit <a href="http://localhost:3000/">http://localhost:3000</a> in your browser</li><li>You should now see Clerk authentication in action — try signing in!</li></ol><p>This was the basic setup — you’re now seeing Clerk in action! 🎉</p><h3>📌 But Wait! One Important Step Left…</h3><p>What we’ve done so far is great for testing — but to make Clerk truly work in a <strong>real-world environment</strong>, you need to connect it to your actual <strong>Clerk project</strong> using <strong>API keys</strong>.</p><p>This ensures that authentication is securely tied to your app and user data.</p><h3>📦 Step 5: Link Clerk with Your Project Dashboard</h3><h4>🧷 1. Create a new Clerk account or sign in :</h4><p>the<a href="https://dashboard.clerk.com/sign-up?_gl=1*1qp2j4j*_gcl_au*MjEzMTYxNTcyMy4xNzQxNTI2NTQ4*_ga*ODg1Mjg3OTA5LjE3NDE1MjY1NDg.*_ga_1WMF5X234K*czE3NDkxOTIyNjckbzgkZzEkdDE3NDkxOTUyMTckajIwJGwwJGgw"> Create a Clerk account⁠</a> or <a href="https://dashboard.clerk.com/?_gl=1*yhc9zb*_gcl_au*MjEzMTYxNTcyMy4xNzQxNTI2NTQ4*_ga*ODg1Mjg3OTA5LjE3NDE1MjY1NDg.*_ga_1WMF5X234K*czE3NDkxOTIyNjckbzgkZzEkdDE3NDkxOTUyMjYkajExJGwwJGgw">sign into the Clerk Dashboard⁠</a>.</p><h4>🧷 2. Create a new Clerk application</h4><ul><li>Click on <strong>“Create Application”</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*Zd_mx2f_zZLUiTj0JjINoA.png" /></figure><ul><li>Customize your SignIn Card and give your app a name (e.g., My Video Lib Auth)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nWS1URTOC_ADsIJ5I9xxQ.png" /></figure><ul><li>Choose the framework you’re using (select <strong>Next.js</strong>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7J0lkxM2rXRvsLN0WAtDg.png" /></figure><p>Since we’ve already completed most of the steps, you just need to add your environment keys to finish the setup.</p><h4>🧰 3. Set up your Clerk environment keys</h4><p>Now you just need to add the API keys to your .env.local file.</p><h4>Set your Clerk API keys</h4><p>Add these keys to your .env.localfile or create it if it doesn’t exist.</p><pre><br>//.env <br><br>NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=#############################<br>CLERK_SECRET_KEY=#############################################</pre><h4>🔁 4. Restart your dev server</h4><p>After saving the keys, restart your server so the environment variables are loaded:</p><pre>npm run dev</pre><h3>☑️ Quick Recap</h3><p>Whether you started by setting up your app first or created the Clerk project before — both approaches are valid. Here’s the simple flow again:</p><blockquote><strong><em>Install Clerk → Wrap with Provider → Use Prebuilt Components → Create Clerk App → Add ENV Keys</em></strong></blockquote><p>That’s it — authentication in minutes🙌</p><h3>What’s Next? — Customize Your Sign In and Sign Up Pages</h3><p>Now that you have the basic Clerk authentication setup working, the next step is to create <strong>custom Sign In and Sign Up pages</strong> tailored to your app’s design and user experience.</p><p>📌 Clerk’s official docs provide a great guide on how to build these custom pages in Next.js — check it out here:<br> 👉 <a href="https://clerk.com/docs/references/nextjs/custom-sign-in-or-up-page">Custom Sign In or Up Page | Clerk Docs</a></p><p>I’m working on a <strong>Part 2 blog post</strong> that will walk you through all these steps in detail — so stay tuned! 🎉</p><p><em>“✨ Thank you for reading! 💖 I hope you found this helpful and inspiring. If you enjoyed it, feel free to share, clap 👏, or leave a comment — I’d love to hear your thoughts! 🌟 Happy coding! 💻😊” — Juvita Saini</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a676fdda73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Node.js and Why Does It Exist?]]></title>
            <link>https://medium.com/@juvitasaini/what-is-node-js-and-why-does-it-exist-4076e0078497?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/4076e0078497</guid>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[javascript-engine]]></category>
            <category><![CDATA[what-is-node-js]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 16:46:10 GMT</pubDate>
            <atom:updated>2025-04-27T17:09:57.410Z</atom:updated>
            <content:encoded><![CDATA[<p>Our JavaScript code can run because of <strong><em>something</em></strong> — and that something is already there inside the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAPUpldqja4c4Twha8eLOg.png" /></figure><p>Let’s write some code in browser :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*8DgJ3_LZaW-4wyj3vqICRQ.png" /></figure><p>This piece of code is running because <em>something</em> is making it run!<br> It’s not magic — there’s actually an engine behind it.</p><p><strong>Hold on</strong>, we’ll talk about that engine in a bit.But first, what if you type the same line of code directly into your laptop’s terminal?</p><p><strong>Here’s what you have to do :<br></strong>Open your laptop’s terminal and try the same code which you tried in the browser. See the image attached, this was my laptop’s response :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*TYZrXuR3kt-uLLwtjb-5xQ.png" /></figure><p>And… it doesn’t work! Ummm… why??</p><p>Because JavaScript needs an <strong>environment</strong> to run — it doesn’t just run by itself. So this means it’s not magic — it needs <em>something</em> to run. That environment could be <strong>Node.js</strong> or something else!</p><h3>So, What About Node.js?</h3><p>I already have Node.js installed on my laptop (you can install it too, based on your operating system).But then you might ask: <strong>“If I had Node.js installed, why didn’t it work before?”</strong></p><p><strong>Answer</strong>: Because you need to <strong>enter</strong> into that environment first by typing node in the terminal (I&#39;m using a Mac, btw)!</p><p>Here’s exactly what you should do:</p><ol><li>Open your terminal and type node.</li><li>Then type:</li></ol><pre>console.log(&quot;Hello World!&quot;);</pre><p>3. and press Enter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*ELs9LJNwjzGH6hzo7GuYRA.png" /></figure><p><strong>Boom!</strong></p><p>Now you are <em>inside</em> the Node.js environment, running JavaScript outside the browser, directly on your machine.</p><p>That mysterious <em>something</em>?<br> Yeah, it’s called <strong>Node.js</strong>!</p><p>Hope it’s clear now what Node.js really is!</p><h3>Why Does Node.js Even Exist?</h3><p>Originally, JavaScript was made just for browsers — to make web pages interactive.</p><p>But developers thought:</p><p><strong>“Hey, JavaScript is easy and powerful… why can’t we use it outside the browser too?”</strong></p><p>That’s where <strong>Node.js</strong> comes in!</p><p>Node.js allows us to run JavaScript <strong>outside</strong> of the browser — directly on our computers, servers, and even in cloud systems. Thanks to Node.js, we can now build <em>backend servers</em>, <em>APIs</em>, <em>real-time apps</em>, <em>tools</em>, and so much more — all using JavaScript!</p><blockquote><strong><em>Node.js = JavaScript’s passport to the outside world 🌎.<br></em></strong>Node.js is like giving JavaScript a superpower — so it can work outside the browser too! 🌍💥 N<em>ode.js made JavaScript leave home (the browser) and explore the world!”</em> 😄🚀</blockquote><h3>Conclusion</h3><p>I want to highlight one important thing: In the <strong>browser</strong>, the “something” that lets JavaScript run is the <strong>JavaScript engine</strong> — for example, Chrome uses the <strong>V8 engine</strong>. For running JavaScript <strong>outside</strong> the browser (like on your laptop, servers, or in the cloud), we need an environment like <strong>Node.js</strong> (or similar tools).</p><p><strong>Bottom line:</strong><br> JavaScript always needs <em>something</em> — an engine or an environment — to understand and run the code. It can’t run completely on its own!</p><p><em>Hope you now feel a little more comfortable with Node.js! 🚀🎀</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4076e0078497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Blocking: How Absolute Positioning Can Block Your Hover Effects]]></title>
            <link>https://medium.com/@juvitasaini/event-blocking-how-absolute-positioning-can-block-your-hover-effects-72976cbb5b44?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/72976cbb5b44</guid>
            <category><![CDATA[absolute]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[hover]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 21:20:20 GMT</pubDate>
            <atom:updated>2025-03-31T21:42:47.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AavfhKrfvSa9eIAY" /><figcaption>Photo by <a href="https://unsplash.com/@saif71?utm_source=medium&amp;utm_medium=referral">Saif71.com</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Help! My Hover Effects Are Ghosting Me! 👻</h3><h3>The Mystery of Disappearing Hover Effects Solved</h3><p>Ever created the perfect hover effect for your image, only to find your mouse cursor acting like it has a restraining order against it? 🤔 Your CSS is flawless (or so you thought), but somehow your hover effects are playing hard to get!</p><h3>The Invisible Blocker Drama 🕵️‍♀️</h3><p>Picture this scenario: You’ve got a beautiful image 🖼️ with a hover effect that should make it zoom, fade, or do a little dance. But you’ve also placed some absolutely positioned elements in the same container — maybe some text overlays or fancy buttons.</p><p>When you hover… NOTHING HAPPENS! 😱</p><p><strong>Plot twist:</strong> Those absolute elements are like sneaky photobombers in your DOM! Even though you can’t see them (they might be transparent), they’re physically there, intercepting your mouse events before they reach your image.</p><h3>What’s Actually Happening? 🧐</h3><p>It’s like trying to pet a cat through a glass window. You can see the cat 🐱, but you’re actually touching the glass, not the cat. In CSS terms:</p><ul><li>Your absolute elements create an invisible layer above your image</li><li>Your mouse is interacting with this invisible layer</li><li>Your image never gets the memo that you’re trying to hover over it</li><li>Your hover effect sits in the corner crying 😢</li></ul><h3>Two Super Easy Fixes! 🛠️</h3><h3>Solution #1: Give Your Image Superpowers with z-index ⚡</h3><pre>.my-image {<br>  position: relative;<br>  z-index: 999; /* UNLIMITED POWER! */<br>}</pre><pre>.sneaky-absolute-element {<br>  position: absolute;<br>  z-index: 1;<br>}</pre><p>This is like giving your image a jetpack to fly above the absolute elements. Now your image is on top and can receive all the hover love directly!</p><h3>Solution #2: Ghost Mode with pointer-events (My Favorite!) 👍</h3><pre>.sneaky-absolute-element {<br>  position: absolute;<br>  pointer-events: none; /* Poof! I&#39;m a ghost now! */<br>}</pre><p>With pointer-events: none, your absolute elements become like ghosts - visible but unable to interact with the mouse. Your cursor passes straight through them to the image below. Spooky but effective! 👻</p><h3>Which Solution Should You Choose? 🤷‍♀️</h3><ul><li><strong>Use z-index</strong> when you want to play “king of the hill” with your elements but still want interaction with everyone</li><li><strong>Use pointer-events: none</strong> when you want your absolute elements to be seen but not heard (or clicked, or hovered)</li></ul><h3>The Big Takeaway 🧠</h3><p>Next time your hover effects mysteriously vanish, remember: there might be an invisible element playing goalie and blocking all your mouse events! Check for absolute positioned elements and either boost your z-index or make those blockers ghostly with pointer-events: none.</p><p>Problem solved! Your hover effects will be back from the dead! 🧟‍♂️</p><p>Have your CSS elements ever played hide-and-seek with your mouse cursor? Share your CSS horror stories below! 💬</p><p>“✨ Thank you for reading! 💖 I hope you found this helpful and inspiring. If you enjoyed it, feel free to share, clap 👏, or leave a comment — I’d love to hear your thoughts! 🌟 Happy coding! 💻😊” — Juvita Saini</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72976cbb5b44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 19 New Features: Simplifying with useActionState (Part 1)]]></title>
            <link>https://medium.com/@juvitasaini/react-19-new-features-simplifying-with-useactionstate-part-1-eb76eb07d21d?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb76eb07d21d</guid>
            <category><![CDATA[react-19-updates]]></category>
            <category><![CDATA[useformstatus]]></category>
            <category><![CDATA[react-19-features]]></category>
            <category><![CDATA[useactionstate]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 07:21:07 GMT</pubDate>
            <atom:updated>2024-12-04T07:27:33.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZH4bmKGNGJU9vl17gU8tbw.png" /></figure><h3>Traditional way of creating forms</h3><p>Let’s look at the traditional way of creating forms using<br>1. state for storing the values.<br>2. onChange in the input field for updating the values in the input.<br>2. value in the input field.</p><pre>// states<br>const [name, setName] = useState(&quot;&quot;); // to store name from input field<br>const [error, setError] = useState(null); // To keep error in a state<br>const [isPending, setIsPending] = useState(false); //To track when api call<br>                                             // has started but not completed</pre><pre>//input prop : value and onChange<br>&lt;input value={name} onChange={(event) =&gt; setName(event.target.value)} /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*KxxMS6LNS5gOxXKbpt2NIA.png" /></figure><p><strong>React 19 aims to remove these three (mainly) !</strong></p><p><strong>Let’s see whole code :</strong></p><pre>// Before <br>function UpdateName({}) {<br>  const [name, setName] = useState(&quot;&quot;);<br>  const [error, setError] = useState(null);<br>  const [isPending, setIsPending] = useState(false);<br><br>  const handleSubmit = async () =&gt; {<br>    setIsPending(true);<br>    const error = await updateName(name);<br>    setIsPending(false);<br>    if (error) {<br>      setError(error);<br>      return;<br>    } <br>    redirect(&quot;/path&quot;);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input value={name} onChange={(event) =&gt; setName(event.target.value)} /&gt;<br>      &lt;button onClick={handleSubmit} disabled={isPending}&gt;<br>        Update<br>      &lt;/button&gt;<br>      {error &amp;&amp; &lt;p&gt;{error}&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Focus on the following aspects in the code above:</p><ul><li>State to manage input values, error statefor handling error and isPending statefor tracking api call.</li><li>The use of value and onChange props in input fields.</li></ul><p><strong>Now, imagine you have 10 input fields.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*hJYvGHs4ryb9EOUt1bqXew.png" /></figure><ul><li>This would require either creating a single state object with 10 keys or 10 separate states.</li></ul><pre>  const [formData, setFormData] = useState({<br>    firstName: &#39;&#39;,<br>    lastName: &#39;&#39;,<br>    email: &#39;&#39;,<br>    phone: &#39;&#39;,<br>    streetAddress: &#39;&#39;,<br>    city: &#39;&#39;,<br>    state: &#39;&#39;,<br>    zipCode: &#39;&#39;,<br>    company: &#39;&#39;,<br>    position: &#39;&#39;,<br>  });</pre><ul><li>Additionally, you would need to repeat <strong>value</strong> and <strong>onChange</strong> for each input field, leading to a lot of repetitive code.</li><li>Also 2 extra states for <strong>error</strong> and <strong>isPending</strong> state.</li></ul><p>React 19 aims to <strong>eliminate this extra boilerplate</strong> using the new hook, useActionState, to simplify the process</p><h3>Updated new way of creating forms with Action</h3><p><strong>React 19 focuses on removing these :</strong><br>1. state for storing the values like for input fields, isPending state or error state.<br>2. onChange in the input field for updating the values in the input.<br>2. value in the input field.</p><p><em>Step-by-Step Guide: Using </em><strong><em>useActionState</em></strong><em> in React 19</em></p><p>In React 19, the useActionState hook simplifies the process of handling forms by removing the need for creating individual states and manually managing values. Instead, you can directly access form data in the handler function, streamlining your form creation.</p><p>Here’s how you can use useActionState:</p><h4>1. Set up the useActionState hook</h4><p>useActionState takes two parameters:</p><ul><li><strong>Action Function</strong> : It’s just an async function with a small difference — it takes two parameters. I’ll explain them below. This function runs when the form is submitted, similar to how a submit handler works.</li><li><strong>Initial State</strong>: The starting value of the state is defined here.</li></ul><p>useActionState returns three parameters:</p><ul><li><strong>error</strong> : Contains any error that may occur during the execution of the action function.</li><li><strong>submitAction</strong> : A function that triggers the action (e.g., form submission) when called, typically linked to the form’s onSubmit event.</li><li><strong>isPending : </strong>A boolean that tracks the status of the action function, indicating whether it is currently in progress (pending) or completed.</li></ul><p><strong>Do not loose hope if you did not understood, let’s code step wise with baby steps</strong> :</p><ol><li>Create a state using the useActionState hook.</li></ol><pre>const []=useActionState();</pre><p>2. Write the return arguments.</p><pre>const [error, submitAction, isPending]=useActionState();</pre><p>When we will be using them in below code, you will get use of all these three.<br>3. Pass 2 arguements to the useActionState</p><pre>const [error, submitAction, isPending]=useActionState(submithandler,null);</pre><p>4. Let’s write <strong>submithandler: Action function</strong> that triggers the action when called (e.g., form submission).</p><pre>const submitHandler = async (previousState, formData) =&gt; {<br>   // we will write code here soon<br>  };<br><br>const [error, submitAction, isPending]=useActionState(submithandler,null);</pre><p>5. Now pass this submitAction to the form</p><pre>&lt;form action={submitAction}&gt; // action prop will take submitAction, no onSubmit!<br>....<br>&lt;/form&gt;</pre><p>Now write the <strong>input fields</strong> without onChange and value. Use <strong>error</strong> and <strong>isPending</strong> state returned by the useAction.</p><pre>&lt;form action={submitAction}&gt; // action prop will take submitAction, no onSubmit!<br>&lt;input name=&quot;name&quot; /&gt; {/ No value or onChange needed! /}<br>&lt;button disabled={isPending}&gt;<br>Update<br>&lt;/button&gt;<br>{error &amp;&amp; &lt;p&gt;{error}&lt;/p&gt;}<br>&lt;/form&gt;</pre><p>So you have Almost completed the writing useActionState hook.</p><h3><strong>submitHandler</strong></h3><p>Let’s write submitAction’s Action function “<strong>submitHandler</strong>” which is first argument of the useActionState. This will be triggered when the linked form is submitted.</p><pre>const submitHandler = async (previousState, formData) =&gt; {<br>// formData.get(&#39;name&#39;) retrieves the value from input with name=&quot;name&quot;<br>const name = formData.get(&#39;name&#39;);<br>// Call API to update name<br>const error = await updateName(name);<br>if (error) {<br>return error; // Returning error will set it in the error state<br>}<br>redirect(&quot;/path&quot;);<br>};</pre><p><strong>Whole Code Combined :</strong></p><pre>// After - Using useActionState<br>function UpdateName() {<br><br>const submitHandler = async (previousState, formData) =&gt; {<br>// formData.get(&#39;name&#39;) retrieves the value from input with name=&quot;name&quot;<br>const name = formData.get(&#39;name&#39;);<br>// Call API to update name<br>const error = await updateName(name);<br>if (error) {<br>return error; // Returning error will set it in the error state<br>}<br>redirect(&quot;/path&quot;);<br>};<br><br>const [error, submitAction, isPending] = useActionState(submitHandler, null);<br><br>return (<br>&lt;div&gt;<br><br>&lt;form action={submitAction}&gt;<br>&lt;input name=&quot;name&quot; /&gt; {/ No value or onChange needed! /}<br>&lt;button disabled={isPending}&gt;<br>Update<br>&lt;/button&gt;<br>{error &amp;&amp; &lt;p&gt;{error}&lt;/p&gt;}<br>&lt;/form&gt;<br><br>&lt;/div&gt;<br>);<br>}</pre><p>See, how simple we wrote the code using useActionState.</p><p>Notice the key differences:<br>1. No useState hooks needed for form values, error, or loading state<br>2. No onChange handlers<br>3. No value props<br>4. Form inputs only need a name attribute<br>5. Form uses action prop instead of onSubmit</p><h3>Handling Multiple Input Fields</h3><p>The real power of useActionState shines when dealing with multiple input fields.</p><p>Here’s an example with a complete registration form:</p><pre>function RegistrationForm() {<br><br>const submitHandler = async (previousState, formData) =&gt; {<br>// Easily access all form values<br>const userData = {<br>firstName: formData.get(&#39;firstName&#39;),<br>lastName: formData.get(&#39;lastName&#39;),<br>email: formData.get(&#39;email&#39;),<br>phone: formData.get(&#39;phone&#39;),<br>streetAddress: formData.get(&#39;streetAddress&#39;),<br>city: formData.get(&#39;city&#39;),<br>state: formData.get(&#39;state&#39;),<br>zipCode: formData.get(&#39;zipCode&#39;),<br>company: formData.get(&#39;company&#39;),<br>position: formData.get(&#39;position&#39;)<br>};<br>try {<br>await registerUser(userData);<br>redirect(&#39;/dashboard&#39;);<br>} catch (error) {<br>return error.message;<br>}<br>};<br><br><br>const [error, submitAction, isPending] = useActionState(submitHandler, null);<br><br>return (<br>&lt;form action={submitAction}&gt;<br>&lt;input name=&quot;firstName&quot; placeholder=&quot;First Name&quot; /&gt;<br>&lt;input name=&quot;lastName&quot; placeholder=&quot;Last Name&quot; /&gt;<br>&lt;input name=&quot;email&quot; type=&quot;email&quot; placeholder=&quot;Email&quot; /&gt;<br>&lt;input name=&quot;phone&quot; placeholder=&quot;Phone&quot; /&gt;<br>&lt;input name=&quot;streetAddress&quot; placeholder=&quot;Street Address&quot; /&gt;<br>&lt;input name=&quot;city&quot; placeholder=&quot;City&quot; /&gt;<br>&lt;input name=&quot;state&quot; placeholder=&quot;State&quot; /&gt;<br>&lt;input name=&quot;zipCode&quot; placeholder=&quot;Zip Code&quot; /&gt;<br>&lt;input name=&quot;company&quot; placeholder=&quot;Company&quot; /&gt;<br>&lt;input name=&quot;position&quot; placeholder=&quot;Position&quot; /&gt;<br>&lt;button type=&quot;submit&quot; disabled={isPending}&gt;<br>{isPending ? &#39;Registering...&#39; : &#39;Register&#39;}<br>&lt;/button&gt;<br>{error &amp;&amp; &lt;p className=&quot;error&quot;&gt;{error}&lt;/p&gt;}<br>&lt;/form&gt;<br>);<br>}<br><br>// see how clean code looks 🎲 🚀</pre><p><strong>Benefits of useActionState</strong></p><p>1. <strong>Reduced Boilerplate</strong>: No need for multiple useState hooks or onChange handlers<br>2. <strong>Automatic Form State Management:</strong> Form values are automatically collected and available in the submitHandler<br>3. <strong>Built-in Loading State:</strong> isPending is handled automatically<br>4.<strong> Simple Error Handling:</strong> Just return an error from the action function to display it<br>5. <strong>Better Performance: </strong>Fewer re-renders as there’s no state updates on every keystroke</p><p><strong>Using </strong><strong>useFormStatus with useActionState</strong></p><p>If you’re using a reusable component, such as replacing a standard button with a custom SubmitButton, you&#39;ll need to pass the isPending prop to ensure the actual button within the SubmitButton component can utilize it.</p><p>The traditional approach for this is shown below :</p><pre>&lt;SubmitButton prop={isPending}&gt;Register&lt;/SubmitButton&gt;  <br><br>SubmitButton=({isPending})=&gt;{<br>return (<br> &lt;button disabled={isPending}&gt;Submit&lt;/button&gt;<br>)<br>}</pre><p>With useFormStatus :</p><pre>&lt;SubmitButton prop={isPending}&gt;Register&lt;/SubmitButton&gt;  ❌ No need to pass prop<br></pre><pre>import { useFormStatus } from &#39;react-dom&#39;;<br><br>// Button Component : Child<br>function SubmitButton({ children }) {<br>const { pending } = useFormStatus();<br>return (<br>&lt;button type=&quot;submit&quot; disabled={pending}&gt;<br>{pending ? &#39;Submitting...&#39; : children}<br>&lt;/button&gt;<br>);<br>}<br><br>// Form : Parent<br>function RegistrationForm() {<br>const submitHandler = async (previousState, formData) =&gt; {<br>// ... handler logic<br>};<br>const [error, submitAction] = useActionState(submitHandler, null);<br>return (<br>&lt;form action={submitAction}&gt;<br>&lt;input name=&quot;username&quot; /&gt;<br>&lt;input name=&quot;password&quot; type=&quot;password&quot; /&gt;<br>{/ Use the custom button component /}<br>&lt;SubmitButton&gt;Register&lt;/SubmitButton&gt; <br>{error &amp;&amp; &lt;p&gt;{error}&lt;/p&gt;}<br>&lt;/form&gt;<br>);<br>}</pre><p>To access isPending value in the child component of form componnent, mainly the submit button.Think of useFormStatus as a walkie-talkie 📻 that tells child components inside a form whether something is loading. It’s super helpful when you want your submit button (which lives inside the form) to know when the form is busy.</p><p><strong>Conclusion</strong></p><p>React 19’s useActionState hook represents a significant step forward in simplifying form handling in React applications. It reduces boilerplate code, makes form state management more intuitive, and provides built-in solutions for common form-related challenges like loading and error states.</p><p>In Part 2, we’ll dive deeper into the exciting new features of React 19. In upcoming blogs, we’ll also explore advanced capabilities of useActionState, including topics like form validation, file uploads, seamless integration with existing form libraries, and additional powerful hooks.</p><p>“✨ Thank you for reading! 💖 I hope you found this helpful and inspiring. If you enjoyed it, feel free to share, clap 👏, or leave a comment — I’d love to hear your thoughts! 🌟 Happy coding! 💻😊” — Juvita Saini</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb76eb07d21d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useRef : understand with scroll example]]></title>
            <link>https://medium.com/@juvitasaini/useref-understand-with-scroll-example-75ad7139557b?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/75ad7139557b</guid>
            <category><![CDATA[useref-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[useref]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 09:41:04 GMT</pubDate>
            <atom:updated>2024-07-02T19:35:10.758Z</atom:updated>
            <content:encoded><![CDATA[<h3>useRef : understand with scroll example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S-N72L0KmKF0UFlT" /><figcaption>Photo by <a href="https://unsplash.com/@kalebtapp?utm_source=medium&amp;utm_medium=referral">kaleb tapp</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Incase you want to show some changes on screen, but do not want the re-render to happen. Refs are like state variables that don’t trigger re-renders when you set them.</p><p>So Let’s understand with Example</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*Phb91PsUeimI0d8jJXyyRw.png" /></figure><p>You have four images and you want to add a scroll effect. In this case, before and after scrolling, the images will remain the same; the only difference will be their positions. Before we had 4 picture and after we have same 4 pictures, data remains same.</p><p>So, if we could scroll without re-rendering, wouldn’t that be a better approach?</p><h3>Let’s code it :</h3><h3>a) Creating Reference</h3><ol><li>Import useRef</li></ol><pre>import { useRef } from &#39;react&#39;;</pre><p>2. Create a reference: calling useRef returns an object with a current</p><pre>// Create a reference using useRef<br>const scrollContainerRef = useRef(null); // useRef returns an object with a `current` property</pre><pre> you are sending null as initial value and </pre><pre>  it wil return --&gt;   { current : null }<br></pre><p>3. Refer to the Container of images by using “scrollContainerRef”</p><pre>// Reference the container of images using scrollContainerRef<br>&lt;div ref={scrollContainerRef}&gt;<br>  {images.map(image =&gt; (<br>    // Render your images here<br>    &lt;img key={image.id} src={image.url} alt={image.alt} /&gt;<br>  ))}<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWubmjBITOFe4Eh41SE3vg.png" /></figure><p>now, at this point we have a reference to this DOM element that we can manipulate directly.</p><h3>b) Using Reference</h3><p>Let’s manipulate the position of this element using the reference we created with useRef.</p><p>Look at image carefully, the hand is controlling person, same way we will control the image with the help of reference which is acting as threads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cPgqlFAR_gL6uCiI" /><figcaption>Photo by <a href="https://unsplash.com/@agni11?utm_source=medium&amp;utm_medium=referral">Sivani Bandaru</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li>first Create function for scroll (<strong>handleScroll</strong>)<br>scrollContainerRef.current is : <br>1) { current : null }, then don’t run code<br>2) { current : &lt;div ref={scrollContainerRef}&gt; ……&lt;/div&gt; }, then run</li></ul><p>it means we need to check that srollContainerRef.current is not null before writing logic to scroll images using reference.</p><p><strong>Function and explanation</strong></p><pre>const handleScroll = (direction) =&gt; {<br>    if (scrollContainerRef.current) {<br>      const container = scrollContainerRef.current; <br>      const scrollAmount = container.clientWidth; // img container width   <br>     if (direction === &#39;next&#39;) {<br>        // for all images except last image increment<br>        container.scrollLeft += scrollAmount;<br>        // if last image, then <br>        if (container.scrollLeft &gt;= container.scrollWidth - container.clientWidth) {<br>          container.scrollLeft = 0;<br>        }<br>      } else {<br>        container.scrollLeft -= scrollAmount;<br>        if (container.scrollLeft &lt;= 0) {<br>          container.scrollLeft = container.scrollWidth - container.clientWidth;<br>        }<br>      }<br>    }<br>  };</pre><ul><li><strong>container</strong> stores the image container element that div<br><em> const container = scrollContainerRef.current;</em></li><li>container.clientWidth gives us the viewable width of the container (in easy language, it’s giving width of the element which is div in our case, that div which are are refering to i.e in which we passes <strong>ref={scrollContainerRef}. L</strong>ike in our case, the viewable part will be 1 image which is taking full space of the container. so u can assume that<br>scrollAmount<strong><em> </em></strong>will contain width of container of image. <br> <br> <em>const </em><strong><em>scrollAmount</em></strong><em> = container.clientWidth;</em></li><li>Next we have updated the horizontal position of the container by updating <strong>container.scrollLeft. </strong>Go through logic which is easy to grasp, give it a read. Point here is not that logic, but rather how we’re utilizing useRef to directly access and manipulate the DOM element (the “div” in this case). This approach with useRef in React is same as how we traditionally used methods like document.querySelector() in vanilla JavaScript to select and manipulate DOM elements.</li><li>Add Buttons to scroll left and right:<br><em>&lt;button onClick={() =&gt; </em><strong><em>handleScroll(‘prev’)</em></strong><em>}&gt;Previous&lt;/button&gt;<br> &lt;button onClick={() =&gt; </em><strong><em>handleScroll(‘next’)</em></strong><em>}&gt;Next&lt;/button&gt;</em></li></ul><p>Whole Code : go to any React online editor and paste below code</p><pre>import React, { useRef } from &#39;react&#39;;<br>export function App() {<br>  const scrollContainerRef = useRef(null); const images = [<br>    {<br>      id: 1,<br>      url: &#39;https://images.unsplash.com/photo-1575936123452-b67c3203c357?q=80&amp;w=1470&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&#39;,<br>      alt: &#39;Hand Picked&#39;,<br>      title: &#39;Camera&#39;,<br>    },<br>    {<br>      id: 2,<br>      url: &#39;https://images.unsplash.com/photo-1488372759477-a7f4aa078cb6?q=80&amp;w=1470&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&#39;,<br>      alt: &#39;New Arrivals&#39;,<br>      title: &#39;Image&#39;,<br>    },<br>    {<br>      id: 3,<br>      url: &#39;https://images.unsplash.com/photo-1517329782449-810562a4ec2f?q=80&amp;w=1463&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&#39;,<br>      alt: &#39;Our Store&#39;,<br>      title: &#39;Phone&#39;,<br>    },<br>    {<br>      id: 4,<br>      url: &#39;https://images.unsplash.com/photo-1598214886806-c87b84b7078b?q=80&amp;w=1450&amp;auto=format&amp;fit=crop&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&#39;,<br>      alt: &#39;Blooming Day&#39;,<br>      title: &#39;Food&#39;,<br>    },<br>  ];<br>const handleScroll = (direction) =&gt; {<br>    if (scrollContainerRef.current) {<br>      const container = scrollContainerRef.current;<br>      const scrollAmount = container.clientWidth;<br>      if (direction === &#39;next&#39;) {<br>        container.scrollLeft += scrollAmount;<br>        if (container.scrollLeft &gt;= container.scrollWidth - container.clientWidth) {<br>          container.scrollLeft = 0;<br>        }<br>      } else {<br>        container.scrollLeft -= scrollAmount;<br>        if (container.scrollLeft &lt;= 0) {<br>          container.scrollLeft = container.scrollWidth - container.clientWidth;<br>        }<br>      }<br>    }<br>  };<br>  return (<br>    &lt;div style={{ width:&quot;400px&quot;, margin: &#39;0 auto&#39;, padding: &#39;20px&#39;, overflow: &#39;hidden&#39; }}&gt;<br>      &lt;div <br>        ref={scrollContainerRef} <br>        style={{ <br>          display: &#39;flex&#39;, <br>          overflowX: &#39;hidden&#39;, <br>          scrollBehavior: &#39;smooth&#39;, <br>          width: &#39;100%&#39; <br>        }}<br>      &gt;<br>        {images.map(image =&gt; (<br>          &lt;div <br>            key={image.id} <br>            style={{ <br>              flex: &#39;0 0 100%&#39;, <br>              minWidth: &#39;100%&#39;, <br>              display: &#39;flex&#39;, <br>              flexDirection: &#39;column&#39;, <br>              alignItems: &#39;center&#39;, <br>              justifyContent: &#39;center&#39;, <br>              textAlign: &#39;center&#39; <br>            }}<br>          &gt;<br>            &lt;img <br>              src={image.url} <br>              alt={image.alt} <br>              style={{ maxWidth: &#39;100%&#39;, height: &#39;auto&#39; }}<br>            /&gt;<br>            &lt;h2&gt;{image.title}&lt;/h2&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>      &lt;div style={{ display: &#39;flex&#39;, justifyContent: &#39;space-between&#39;, marginTop: &#39;20px&#39; }}&gt;<br>        &lt;button onClick={() =&gt; handleScroll(&#39;prev&#39;)}&gt;Previous&lt;/button&gt;<br>        &lt;button onClick={() =&gt; handleScroll(&#39;next&#39;)}&gt;Next&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Code: <a href="https://playcode.io/1924741">https://playcode.io/1924741</a><br>Preview: <a href="https://preview-1924741.playcode.io/">https://preview-1924741.playcode.io/</a></p><p><strong>Key Takway :</strong></p><p>The key takeaway is that we’re altering the visual position of elements without triggering a re-render of the component. This efficient DOM manipulation is made possible through useRef, which allows us to directly access and modify the DOM element outside of React’s usual reconciliation process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75ad7139557b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useMemo vs memo in React ]]></title>
            <link>https://medium.com/@juvitasaini/usememo-vs-memo-in-react-8c9da370dbdc?source=rss-6c971dc4f924------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c9da370dbdc</guid>
            <category><![CDATA[optmization]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[usememo]]></category>
            <category><![CDATA[memo]]></category>
            <dc:creator><![CDATA[Juvita Saini]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 07:12:26 GMT</pubDate>
            <atom:updated>2024-06-26T04:03:54.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lIzOvWpK1qbplHP7" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Optimizing Performance in React: A Simple Guide to useMemo and memo</h3><p>When optimizing performance in a React application, two useful tools at your disposal are useMemo and memo. While both serve the purpose of optimization, they are used in different scenarios and ways. Let&#39;s explore these differences with examples.</p><h4>Understanding useMemo</h4><p><strong>In simple terms,</strong> useMemo deals with regular functions like factorial(n) or sum(a, b), among others. Every time a function runs, it checks if it’s seen the same inputs before. If it has, there must already be a result stored in the cache. So, why not grab that result and return it without doing the calculation again? Exactly, no need for unnecessary recalculation.</p><p>For instance, if a user inputs 2 and then inputs 2 again, a standard function would perform the entire calculation again. However, with useMemo after the user first enters 2, the result is saved. So, if the user enters the same input again, useMemo won’t recalculate; instead, it will retrieve the stored result.</p><p><strong>In technical terms,</strong>useMemo is a hook provided by React that allows developers to optimize expensive calculations by memorizing the result of a function given specific inputs. It ensures that the function is only re-computed when one of its dependencies changes, thereby saving computational resources.</p><p>Syntax: The syntax for useMemo is similar to useEffect:</p><pre>useMemo(function, dependencies);</pre><p><strong>Example</strong>: Factorial Function</p><p>Consider a scenario where you have a factorial function that takes an integer n as input and returns the factorial of that number. If a user repeatedly enters the same number, recalculating the factorial every time would be unnecessary. Instead, you can use useMemo to cache the result and avoid redundant computations.</p><pre>// Before using useMemo<br>function factorial(n) {<br>  let result = 1;<br>  for (let i = 2; i &lt;= n; i++) {<br>    result *= i;<br>  }<br>  return result;<br>}<br><br>const result = factorial(5); // Recalculated every time<br><br>// After using useMemo<br>import { useMemo } from &#39;react&#39;;<br><br>function MyComponent({ n }) {<br>  const result = useMemo(() =&gt; factorial(n), [n]);<br><br>  return &lt;div&gt;{result}&lt;/div&gt;;<br>}</pre><p>In the above example, useMemo wraps around the factorial function, ensuring that <strong>it&#39;s only recomputed when </strong><strong>n changes.</strong></p><p>In short, useMemo is particularly for optimizing functions but what about Functional components ???? or say React Components ??????<br>I know they are also a function but they are not normal function so using using useMemo is not a right thing to do so, React said “Ok ! I have some thing for optimizing React Components too : memo”</p><h4>Diving into memo</h4><p><strong>In Layman Language, </strong>If Parent Component re-renders then the child will too re-render(normal behavior) but in case their is a child component whose props are not changed and everything else is same, means that change in Parent is not affecting it then why to re-render this child component, lets optimize it. Hello React !! give us a solution for this problem, React said you can use: memo for optimizing that child component, whenver props don’t change, i should not re-render.</p><p><strong>In Technical Language,</strong>While useMemo is designed for optimizing expensive calculations, memo is tailored for optimizing component rendering. React&#39;s memo is a higher-order component that prevents a functional component from re-rendering unless its props change. This is particularly useful for components that receive complex objects as props and only need to update under certain conditions.</p><p>Syntax:</p><pre>const ReactComponent=memo(ReactComponentDefinition);</pre><p><strong>Example: Optimizing Component Rendering</strong></p><p>Imagine a component that receives a large dataset as a prop and renders a list based on this data. If the dataset doesn’t change frequently, using memo can prevent unnecessary re-renders, improving performance.</p><pre>import React, { memo } from &#39;react&#39;;<br><br>const ListComponent = memo(({ items }) =&gt; (<br>  &lt;ul&gt;<br>    {items.map(item =&gt; (<br>      &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;<br>    ))}<br>  &lt;/ul&gt;<br>));<br><br>export default ListComponent;</pre><p>In this example, ListComponent will only re-render if its items prop changes, thanks to memo.</p><h4>Code Example which includes both memo and useMemo</h4><pre>import React, { memo, useMemo } from &#39;react&#39;;<br><br>const ListComponent = memo(({ items }) =&gt; (<br>  &lt;ul&gt;<br>    {items.map(item =&gt; (<br>      &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;<br>    ))}<br>  &lt;/ul&gt;<br>));<br><br>function MyComponent({ n }) {<br>  const result = useMemo(() =&gt; factorial(n), [n]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;ListComponent items={[{ id: 1, name: &#39;Item 1&#39; }, { id: 2, name: &#39;Item 2&#39; }]} /&gt;<br>      &lt;div&gt;{result}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Helper function<br>function factorial(num) {<br>  let result = 1;<br>  for (let i = 1; i &lt;= num; i++) {<br>    result *= i;<br>  }<br>  return result;<br>}<br><br>export default MyComponent;</pre><h4>Summary</h4><p>Both useMemo and memo are essential tools in a React developer&#39;s toolkit for optimizing performance. useMemo is used to optimize expensive calculations by caching results, while memo is used to prevent unnecessary re-renders of functional components. By understanding when and how to use each, developers can significantly improve the efficiency of their React applications.</p><p>Remember, while optimization is important, it should be applied judiciously. Always measure and identify bottlenecks before applying these techniques to ensure they provide actual benefits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c9da370dbdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>