<?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 Manish Giri Goswami on Medium]]></title>
        <description><![CDATA[Stories by Manish Giri Goswami on Medium]]></description>
        <link>https://medium.com/@manishgcodes?source=rss-992c8eff52fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gEo9QlFo16XrsKDzd52ZRQ.jpeg</url>
            <title>Stories by Manish Giri Goswami on Medium</title>
            <link>https://medium.com/@manishgcodes?source=rss-992c8eff52fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:12:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manishgcodes/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 Web Workers Helped Me Solve a JavaScript Heap Out of Memory Error]]></title>
            <link>https://manishgcodes.medium.com/how-web-workers-helped-me-solve-a-javascript-heap-out-of-memory-error-45053496e436?source=rss-992c8eff52fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/45053496e436</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[heap-out-of-memory]]></category>
            <category><![CDATA[webworker]]></category>
            <dc:creator><![CDATA[Manish Giri Goswami]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 05:39:37 GMT</pubDate>
            <atom:updated>2026-06-01T05:39:37.356Z</atom:updated>
            <content:encoded><![CDATA[<p>👨🏻‍💻<strong>Hello Devs,<br></strong>At some point, most of us have worked on a feature that needed heavy calculations or had to process a large amount of data in a very short time. The usual solution is simple: send the work to the backend, let the server do the heavy lifting, and return the result when it’s ready.</p><ul><li><em>But what happens when that is not an option?</em></li><li><em>What if users need the result instantly?</em></li><li><em>What if sending data to the server adds too much delay?</em></li></ul><p>Or what if the calculation is so heavy that your application starts freezing, making the whole experience feel slow and broken?</p><p>Naturally, the next thought is: <strong><em>Why not do everything in the browser itself ?</em></strong>Sounds reasonable… until the browser starts struggling with the workload.<br>So the real question becomes:</p><p><strong><em>How much can a browser actually handle, and what happens when JavaScript starts running out of memory?</em></strong></p><h3>📜My Story</h3><p>Let me tell you what happened when I got stuck in a situation like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oItDfjzp7nqPJhL_cKOhdQ.png" /></figure><p>Since everything was already available in the frontend, my first instinct was to optimise the application as much as possible. I tried different approaches, reduced unnecessary processing, cleaned up a few things, and squeezed out every bit of optimisation I could think of.</p><p>But honestly, it wasn’t helping much.</p><p>The browser was still crashing on the user’s machine with the error message: <strong><em>heap out of memory</em></strong></p><p>At that point, I felt like I had hit a wall. There wasn’t much room left for optimisation. The problem was clearly bigger than a few code improvements, and I knew I needed a different approach.</p><p>Then something clicked.</p><p>On the backend, whenever we need to handle heavy work, we often rely on workers to move that work away from the main execution flow. So I started wondering:</p><p><strong><em>Do we have something similar on the frontend?</em></strong></p><p>Turns out, we do.</p><p>Frontend applications have workers too. We have Service Workers, Web Workers, and a few other worker APIs depending on the use case.</p><p>And that’s when I thought I had finally found the solution.</p><p>If Web Workers run on a separate thread, maybe I could move the heavy calculation there and get around the memory issue altogether.</p><p>At that moment, it felt like I had hit the jackpot.</p><p>Web Workers seemed like the perfect solution to my problem.</p><p>Let’s dig a little deeper and see why.</p><h3>💡What Are Web Workers?</h3><p>To understand whether Web Workers can help us with memory-heavy tasks, we first need to understand what they actually are.</p><p>By default, JavaScript running in the browser executes on the main thread. This is the same thread responsible for handling user interactions, updating the UI, processing events, and running your application code.</p><p>This is why a heavy calculation can become a problem. If JavaScript spends several seconds processing a large dataset, the main thread becomes busy, and the browser cannot respond to user actions smoothly. Buttons stop responding, animations freeze, and the application starts feeling stuck.</p><p>Web Workers were introduced to solve exactly this problem.</p><p>A Web Worker allows JavaScript code to run on a separate thread, independent of the main thread. This means heavy computations can be moved away from the UI thread, allowing the application to remain responsive while the work continues in the background.</p><p>However, Web Workers are not just “background functions.” They run in their own execution context, have their own event loop, and cannot directly access the DOM. Communication between the main thread and a worker happens through message passing using APIs such as <strong>postMessage()</strong>.</p><p>This isolation is what makes Web Workers powerful for CPU-intensive tasks, but it also raises an interesting question.</p><p>If a Web Worker runs in its own execution environment, what does that mean for memory?</p><h3>🧠What Does That Mean for Memory?</h3><p>When I first learned that Web Workers run on a separate thread, my immediate thought was:</p><p>“If they run on a separate thread, do they also get their own memory?”</p><p>The short answer is yes.</p><p>In browsers like Chrome, JavaScript runs inside a browser tab process managed by the JavaScript engine. The main thread has its own JavaScript heap, and every Web Worker gets its own separate heap as well.</p><p>This detail is important because a JavaScript thread does not automatically get access to all the available RAM on a user’s machine.</p><p>Instead, the JavaScript engine (e.g. V8) places a limit on how large a single heap can grow. These limits exist to keep memory management predictable and prevent a single script from consuming excessive resources.</p><p>Because of this, a thread can run out of memory even when the machine still has plenty of free RAM available. The error is not necessarily telling you that the computer has no memory left. It often means that the JavaScript heap for that particular thread has reached its allowed limit.</p><p>This is where Web Workers become useful for memory-heavy workloads.</p><p>Since each worker has its own independent heap, a large task can be divided across multiple workers instead of forcing a single thread to hold all the data and perform all the processing. In practice, this can increase the total amount of memory available to your application because the workload is now spread across multiple heaps rather than being constrained by just one.</p><p>At this point, it might sound like Web Workers give us unlimited memory.</p><p>They don’t.</p><p>While the main thread and Web Workers have separate heaps, all of those heaps still belong to the same browser tab process. The browser and operating system continue to enforce memory limits on that process as a whole.</p><p>So while Web Workers can help overcome the memory limits of a single JavaScript thread, they cannot bypass the overall memory limits of the browser tab.</p><p>There is one more thing to keep in mind.</p><p>If large amounts of data are copied between workers and the main thread, memory usage can grow very quickly. In some cases, the extra memory consumed by these copies can reduce or even eliminate the benefits of splitting the work across multiple workers.</p><p>So the real advantage of Web Workers is not unlimited memory. The advantage is that they provide additional independent heaps, allowing heavy computations to be distributed across multiple threads while still staying within the browser’s overall memory budget.</p><h3>🤔How to Use a Web Worker ?</h3><p>Now that we understand what Web Workers are and how they can help with heavy workloads, let’s see how we can use them in a React and TypeScript application.</p><p>We’ll use a simple example where a large dataset is sent to a worker for processing. In real-world applications, this could be data transformation, report generation, file processing, complex calculations, or any CPU-intensive task.</p><h4>Step 1: Create a Worker</h4><p>Create a new file named data-processor.worker.ts.</p><pre>self.onmessage = (event: MessageEvent&lt;number[]&gt;) =&gt; {<br>  const dataset = event.data;<br>  const processedData = dataset.map((value) =&gt; value * 2);<br>  self.postMessage(processedData);<br>};<br>export {};</pre><p>This worker waits for data from the main thread, processes it, and sends the result back.</p><p><strong>Note:</strong> Web Workers do not have access to the DOM. Their primary purpose is to perform computations and communicate results back to the main thread.</p><h4>Step 2: Use the Worker in a React Component</h4><pre>import { useEffect } from &quot;react&quot;;<br><br>function App() {<br>  useEffect(() =&gt; {<br>    const worker = new Worker(<br>      new URL(&quot;./data-processor.worker.ts&quot;, import.meta.url),<br>      { type: &quot;module&quot; }<br>    );<br><br>    const largeDataset = Array.from({ length: 100000 }, (_, index) =&gt; index);<br><br>    worker.postMessage(largeDataset);<br><br>    worker.onmessage = (event: MessageEvent&lt;number[]&gt;) =&gt; {<br>      console.log(&quot;Processed items:&quot;, event.data.length);<br>    };<br><br>    return () =&gt; {<br>      worker.terminate();<br>    };<br>  }, []);<br><br>  return &lt;h1&gt;Web Worker Demo&lt;/h1&gt;;<br>}<br><br>export default App;</pre><p>This creates a worker, sends a dataset to it, waits for the result, and properly terminates the worker when the component unmounts.</p><p><strong>Note:</strong> The new URL(…, import.meta.url) syntax works in modern React setups such as Vite and other ESM-based bundlers.</p><p>🤜🤛<strong>How Communication Works ?</strong></p><p>Communication between the main thread and a worker happens through messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZ2mPhkL521exSgcstaUeQ.png" /></figure><p>The main thread sends data using postMessage(), and the worker receives it through onmessage. Once processing is complete, the worker sends the result back using postMessage(), which is then received by the main thread.</p><p>⚠️ <strong>Once a worker has finished its job, don’t forget to terminate it using </strong><strong>worker.terminate().</strong> Keeping unused workers alive can continue consuming memory and CPU resources, which can become costly in long-running applications.</p><p>⚠️ <strong>Important:</strong> When data is sent between the main thread and a Web Worker using postMessage(), the browser typically creates a copy of that data instead of sharing the original object. For very large datasets, these copies can consume a significant amount of memory and introduce additional processing overhead, reducing the performance benefits of using multiple workers.</p><h4>🤔Can We Create Multiple Web Workers?</h4><p>Absolutely.</p><p>A browser application is not limited to a single Web Worker. You can create multiple workers and distribute work across them based on your application’s needs.</p><pre>  const worker1 = new Worker(<br>    new URL(&quot;./data-processor.worker.ts&quot;, import.meta.url),<br>    { type: &quot;module&quot; }<br>  );<br><br>  const worker2 = new Worker(<br>    new URL(&quot;./data-processor.worker.ts&quot;, import.meta.url),<br>    { type: &quot;module&quot; }<br>  );<br><br>  const worker3 = new Worker(<br>    new URL(&quot;./data-processor.worker.ts&quot;, import.meta.url),<br>    { type: &quot;module&quot; }<br>  );</pre><p>In fact, this is a common approach when dealing with large datasets or CPU-intensive operations. Instead of giving one worker all the work, the workload can be divided into smaller chunks and distributed across multiple workers.</p><p>However, there are a few important things to understand before creating workers everywhere.</p><h4>😌More Workers Do Not Always Mean Better Performance</h4><p>A common misunderstanding is that if one worker improves performance, then ten workers must be ten times faster.</p><p>Unfortunately, it doesn’t work that way.</p><p>Every worker is a separate thread that consumes CPU and memory resources. Creating too many workers can actually increase overhead and make the application slower.</p><p>As a general rule, the number of workers should be chosen carefully based on the amount of work being performed and the resources available on the user’s machine.</p><h4>😌Workers Do Not Share Variables</h4><p>Another common misunderstanding is assuming that workers can directly access variables from the main thread.</p><p>They cannot.</p><p>Each worker runs in its own isolated environment. If a worker needs data, that data must be explicitly sent using postMessage() or shared through mechanisms such as SharedArrayBuffer.</p><h4>😌Sending Large Data Has a Cost</h4><p>When data is sent using postMessage(), the browser may need to copy that data between the main thread and the worker.</p><p>For small payloads, this cost is usually negligible.</p><p>For very large datasets, however, these copies can consume significant memory and impact performance.</p><p>This is one of the reasons why blindly creating multiple workers is not always the best solution.</p><h4>😌Workers Are Great for Independent Work</h4><p>Web Workers shine when the work can be split into independent pieces.</p><p>For example:</p><ul><li>Processing large datasets</li><li>File transformations</li><li>Image processing</li><li>Data analysis</li><li>Report generation</li><li>Complex calculations</li></ul><p>The less communication required between workers, the more benefit you are likely to get from using them.</p><p>The key takeaway is simple: Web Workers are powerful, but they are not magic. Creating multiple workers can improve responsiveness and help distribute heavy workloads, but the best results come from carefully splitting work and minimizing unnecessary communication between threads.</p><h3>🏁Final Thoughts</h3><p>Web Workers are truly an amazing utility for frontend developers. They help us move heavy computations away from the main thread and keep our applications responsive, even under demanding workloads.</p><p>But as they say,</p><p><strong>“With great power comes great responsibility.”</strong></p><p>Creating more workers is not always the answer. Understanding how memory works, how data is shared between threads, and how much communication happens between workers is just as important.</p><p>One thing this experience taught me is that optimisation efforts are never wasted. While Web Workers played a huge role in solving my problem, they were most effective when combined with the optimisations I had already made.</p><p>I hope this article helped you understand Web Workers a little better and maybe even solve a problem you’re currently facing.</p><p><strong>🤝Happy coding!</strong></p><p><strong>Thanks for reading!</strong><br>If you found this helpful, let’s connect: 🔗 <a href="https://www.linkedin.com/in/manish-giri-goswami-0b41a1175">LinkedIn</a> | 💻 <a href="https://github.com/manishgcodes">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45053496e436" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Incremental Static Regeneration (ISR): Enable Real-Time Static Page Updates With NextJS]]></title>
            <link>https://manishgcodes.medium.com/next-js-incremental-static-regeneration-isr-explained-how-to-enable-real-time-static-page-b0b11c397bae?source=rss-992c8eff52fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b11c397bae</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Manish Giri Goswami]]></dc:creator>
            <pubDate>Wed, 21 May 2025 04:27:04 GMT</pubDate>
            <atom:updated>2025-11-19T09:48:19.553Z</atom:updated>
            <content:encoded><![CDATA[<p>👨🏻‍💻 <strong>Hello Devs,<br></strong>Next.js has become <em>the</em> go-to frontend framework for modern web apps and we all are using it nowadays for almost all kinds of end-user projects. Whether it’s client-side rendering (CSR), server-side rendering (SSR), or static site generation (SSG), most of us are already familiar with these core rendering strategies. They’re pretty straightforward.</p><p>But today, let’s talk about something slightly more advanced — and incredibly powerful: <strong>Incremental Static Regeneration (ISR).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIOllf4ZgtXe4cfAVtxHew.png" /></figure><h3>⚠️ The Limitations of SSR and SSG</h3><p>Let’s quickly recap why we even need ISR in the first place.</p><p>With <strong>SSR</strong>, every time a user hits a page, the server renders it on the fly and returns the HTML. It’s great for dynamic content, but if thousands of users are hitting your site, that real-time rendering can become a bottleneck. The server ends up doing a lot of heavy lifting — on every single request.</p><p>So, naturally, you might think: <em>Why not just use SSG?</em> Static Site Generation builds HTML pages ahead of time — at build time — and serves them. Those pages get served instantly from the edge, which means blazing-fast load times and almost no server load. But there’s a catch: what happens when your data updates?</p><p>Imagine an e-commerce landing page. Product listings, prices, banners — they all keep changing. You don’t want to rebuild and redeploy your entire app every time something updates in your database. That’s just not scalable.</p><p><strong>Now that you understand the problem, let’s talk about the solution.</strong><br> The brilliant folks behind Next.js came up with <strong>ISR (Incremental Static Regeneration)</strong> to solve exactly this.</p><p>Before we jump into the code, let’s break down how it works in theory.</p><h3>🚀 ISR: Incremental Static Regeneration</h3><p><strong>ISR is Next.js’s answer to this dilemma.</strong></p><p>It’s basically the best of both worlds — SSG and SSR combined. Here’s how it works:</p><ul><li>On build, Next.js generates static HTML pages just like SSG.</li><li>But these pages can <strong>regenerate in the background</strong> on a per-page basis <em>after the site is live</em>.</li><li>You set a revalidate interval for each page. When a request comes in <em>after</em> that interval has passed, Next.js will serve the existing static page, but <strong>trigger a regeneration</strong> in the background.</li><li>Once that new page is generated, it’s cached and served to all subsequent users — until the next regeneration.</li></ul><p>So users still get super-fast responses from the cache, but your content can stay fresh without a full rebuild.</p><p>💡 <strong>Pro Tip: Fresh Content <em>and</em> SEO<br></strong><em>An added benefit of using ISR is that it allows you to serve almost up-to-date content to users </em><strong><em>while still maintaining full SEO benefits</em></strong><em>. Since the regenerated pages are still served as static HTML, </em><strong><em>search engines can crawl and index them effectively — just like traditional static pages</em></strong><em>.</em></p><h3>🔄 On-Demand Revalidation</h3><p>Now here’s the really cool part.</p><p>What if you want to regenerate a page <strong>on-demand</strong> — say, right after a product is updated in your CMS or database?</p><p>Next.js has you covered. You can use the <strong>revalidatePath()</strong> method (in <strong>App Router</strong>) or the <strong>res.revalidate() </strong>method (in <strong>Pages Router</strong>) to programmatically trigger regeneration for a specific path.</p><p>You can call this from:</p><ul><li>API routes</li><li>Action functions (in App Router)</li></ul><p>This gives you full control over when and how your static pages get updated — without rebuilding your entire site.</p><h3>💻 And Now, What You’ve Been Waiting For: The Code</h3><p><strong>Note:</strong><em>The code examples in this blog use the App Router from Next.js 14.</em></p><pre>// app/products/page.tsx<br>interface Product {<br>  id: string<br>  name: string<br>  description: string<br>  price: number<br>}<br><br>// Revalidate the products page in every 1 hour.<br>const oneHour = 60 * 60 // 3600 Seconds<br>export const revalidate = oneHour;<br><br>// Product listing page<br>export default async function ProductListPage() {<br>  const products: Product[] = await fetch(&#39;https://api.example.com/products&#39;)<br>    .then((res) =&gt; res.json())<br>  return (<br>    &lt;main&gt;<br>      &lt;h1&gt;Our Products&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {products.map((product) =&gt; (<br>          &lt;li key={product.id}&gt;<br>            &lt;a href={`/products/${product.id}`}&gt;<br>              &lt;h2&gt;{product.name}&lt;/h2&gt;<br>              &lt;p&gt;${product.description}&lt;/p&gt;<br>              &lt;span&gt;${product.price}&lt;/span&gt;<br>            &lt;/a&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/main&gt;<br>  )<br>}</pre><p>The above page.tsx file is a sample product listing page that fetches product data from an API and renders it on the server. At the top of the file, the revalidate property is set in seconds. In this case, the page is cached for <strong>one hour</strong>. After that time expires, the <strong>next request</strong> will trigger a <strong>background regeneration</strong> of the page with the latest data. Once regenerated, the new version is cached and served for the next one hour—repeating the cycle.</p><pre>// app/api/revalidate/route.ts<br>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br>import { revalidatePath } from &quot;next/cache&quot;;<br><br>export const POST = async (request: NextRequest) =&gt; {<br>  try {<br>    const body = await request.json();<br>    const { path } = body;<br>    if (!path || typeof path !== &quot;string&quot;) {<br>      return NextResponse.json(<br>        { error: &quot;Valid path is required.&quot; },<br>        { status: 400 }<br>      );<br>    }<br>    // Trigger revalidation<br>    revalidatePath(path);<br>    return NextResponse.json({<br>      success: true,<br>      message: `Revalidated path: ${path}`,<br>      timestamp: new Date().toISOString(),<br>    });<br>  } catch (error) {<br>    console.error(&quot;Revalidation error:&quot;, error);<br>    return NextResponse.json(<br>      { error: &quot;Failed to revalidate path.&quot; },<br>      { status: 500 }<br>    );<br>  }<br>};</pre><p>The file “<em>app/api/revalidate/route.ts”</em> above defines a <strong>revalidation API route</strong> that allows you to programmatically trigger regeneration of an ISR-enabled page in <strong>Next.js</strong> — regardless of its scheduled revalidate interval. This is useful when content changes outside of the normal revalidation cycle (e.g., a product update in your CMS or database).</p><p>It uses the revalidatePath() method from next/cache to revalidate a specific page path. When this endpoint receives a POST request with the desired path, it immediately triggers a regeneration of that page in the background. On the next request, users will receive the updated version of the page with the latest data.</p><pre>const revalidatePage = async (path: string) =&gt; {<br>  try {<br>    const response = await fetch(&quot;/api/revalidate&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      },<br>      body: JSON.stringify({ path }),<br>    });<br>    const result = await response.json();<br>    if (!response.ok) {<br>      throw new Error(result.error || &quot;Revalidation failed&quot;);<br>    }<br>    console.log(&quot;✅ Revalidation successful:&quot;, result);<br>  } catch (error) {<br>    console.error(&quot;❌ Error triggering revalidation:&quot;, error);<br>  }<br>};<br><br>// Example usage<br>revalidatePage(&quot;/products&quot;);</pre><p>The revalidatePage function is a utility to programmatically trigger revalidation of a specific ISR-enabled page in a Next.js application. It sends a POST request to the /api/revalidate endpoint with the target page&#39;s path in the request body.</p><p>In this example, we’re calling revalidatePage(&#39;/products&#39;) to revalidate the /products page.</p><p>Now that we’ve covered what ISR is, how to use it, and where it works best, things should be much clearer. <strong>One important point to remember is to secure your revalidation endpoint</strong>. At a minimum, implement a simple x-api-key check to verify the authenticity of incoming requests. This helps keep your server safe and prevents unauthorized access or potential DDOS attacks on your Next.js application.<strong> Ideally, avoid calling this endpoint directly from the frontend—instead, trigger it from your backend for added security</strong>. While you can implement any security measures you find appropriate, this simple approach provides a solid foundation.</p><h3>🏁 Summary</h3><p>We covered how <strong>Incremental Static Regeneration (ISR)</strong> in Next.js lets us serve fast, static pages that can update on a schedule or on demand. We implemented ISR for an e-commerce product listing page, and built an API route for manual revalidation. With ISR, you get fresh data, great performance, and SEO benefits — without constant redeploys. It’s a must-have feature for modern, dynamic sites.</p><p>Other than this, if you have any doubts or suggestions please do put them in the comments.</p><p><strong>🤝Happy coding!</strong></p><p><strong>Thanks for reading!</strong><br>If you found this helpful, let’s connect: 🔗<a href="https://www.linkedin.com/in/manish-giri-goswami-0b41a1175">LinkedIn</a> | 💻<a href="https://github.com/manishgcodes">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b11c397bae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Caching in React Query: Reduce Network Requests and Improve Performance]]></title>
            <link>https://manishgcodes.medium.com/master-caching-in-react-query-reduce-network-requests-and-improve-performance-868291494d40?source=rss-992c8eff52fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/868291494d40</guid>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[react-query]]></category>
            <dc:creator><![CDATA[Manish Giri Goswami]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 16:26:15 GMT</pubDate>
            <atom:updated>2025-05-20T04:48:29.822Z</atom:updated>
            <content:encoded><![CDATA[<h3>Caching in React Query : Reduce Network Requests and Improve Performance</h3><p>👨🏻‍💻 <strong>Hello Devs,<br></strong>React Query ( TanStack Query ) has proven to be an indispensable tool for fetching data in our applications. We frequently rely on its hooks useQuery and useMutation, along with the fetching state ( isLoading, isPending, isFetching and isSuccess etc) values it provides. But here’s the real question: are you truly unlocking the full power of React Query? In this discussion, we’ll delve into some of its lesser-used features and show you how to fully harness its potential for better and more efficient data management.</p><p>In this blog, we’ll explore the purpose and advantages of useQuery, queryKey, gcTime, staleTime, and refetch(). Showing how you can harness its caching features to optimise your web application, making it more efficient and reduce unnecessary complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eykXy61H9J2kAMUGgkt3Mw.jpeg" /></figure><h3>💡Understanding useQuery</h3><p>The useQuery hook is used to fetch data from a GET API (an API that uses the GET method). It takes an object as a parameter, with two essential properties: queryKey and queryFn. While these two are sufficient to make API calls but our goal goes beyond merely making API calls, right?</p><p>We all know that React Query caches the data/response received from an API. However, the same API is often called multiple times with different parameters and payloads. So, how does React Query manage caching efficiently? How does it store data in an organised manner and retrieve it effectively? Let’s understand it.</p><h3>🤔 What is queryKey and Why Does It Matter?</h3><p>The queryKey serves as a unique identifier for cached data in React Query. It helps manage query caching based on these keys. A queryKey must always be an array and can be as simple as a single string inside the array or more complex with multiple strings and nested objects. As long as the queryKey is unique to the data and can be serialised, it can be used effectively.</p><p>When using useQuery, it’s important to include all dependent parameters in the queryKey array, as shown below:</p><pre>// sample payload values for below queryKey examples<br>const productId = &quot;1828&quot;;<br>const page = 1;<br>const pageSize = 10;<br>const searchText = &quot;tshirt&quot;;<br>const sortType = &quot;desc&quot;;</pre><pre>queryKey: [“account-details”]</pre><pre>queryKey: [“product-details”, productId]</pre><pre>queryKey: [“products-list”, page, pageSize, searchText, sortType]</pre><p>These examples illustrate three different ways to structure a queryKey:</p><ul><li>A single static string [“account-details”] for data that doesn’t change frequently.</li><li>A string with a dynamic value [“product-details”, productId] to ensure that each product’s details are uniquely cached.</li><li>A combination of multiple dynamic values [“products-list”, page, pageSize, searchText, sortType] to ensure caching accounts for specific pagination, filters, and sorting configurations, enabling precise and efficient data retrieval.</li></ul><p>By structuring queryKey thoughtfully, you can manage caching in React Query and reduce unnecessary API calls and improve the performance of your application.</p><h3>🤔 What is <strong>gcTime (Garbage Collection Time)</strong></h3><p>gcTime defines the duration (in milliseconds) that cached data remains in memory after it becomes inactive. If not specified, it defaults to <strong>5 minutes (300,000 milliseconds)</strong>. After this period, the data is automatically garbage collected to free up memory.</p><p>Setting a higher gcTime is useful for preserving rarely accessed data, while a lower gcTime is beneficial for optimising memory usage in applications with frequent data updates.</p><p>Example configuration:</p><pre>useQuery([&quot;user-profile&quot;], fetchUserProfile, {<br>  gcTime: 1000 * 60 * 10 // Data will be garbage collected after 10 minutes<br>});</pre><p>This means the cached user-profile data will be retained for 10 minutes after becoming inactive. Adjusting gcTime helps balance memory efficiency and the likelihood of re fetching data from the server.</p><h3>🤔 what is staleTime</h3><p>staleTime determines how long fetched data remains fresh before being marked as stale. By default, it is <strong>0 milliseconds</strong>, meaning data is considered stale immediately after being fetched, triggering a refetch on each component mount.</p><p>Configuring staleTime reduces unnecessary network requests and improves performance. For example:</p><pre>useQuery([“user-profile”], fetchUserProfile, {<br>  staleTime: 1000 * 60 * 5 // Data remains fresh for 5 minutes<br>});</pre><p>This ensures that within 5 minutes, revisiting the user profile route won’t trigger a re-fetch, optimising responsiveness and reducing redundant API calls.</p><p>Note: staleTime should alway be less than or equal to gcTime.</p><h3>🌏 Real-World Example: Fetching User Data</h3><p>Now that we understand queryKey, gcTime, and staleTime, let’s look at a real-world example of fetching user data efficiently.</p><pre>import { useQuery } from &quot;@tanstack/react-query&quot;;<br><br>const oneHour = 1000 * 60 * 60;<br>export const useGetUserData = () =&gt; {<br>  const { data, isLoading, isError, refetch } = useQuery({<br>    queryKey: [&quot;get-user-data&quot;],<br>    queryFn: async() =&gt; await fetch(&quot;https://www.example.com/api/v1/auth/user-data&quot;),<br>    gcTime: oneHour,<br>    staleTime: oneHour,<br>  });<br><br>  return {<br>    userData: data,<br>    isUserDataLoading: isLoading,<br>    isError: isError,<br>    getUserData: refetch    <br>  };<br>};</pre><pre><br>import React from &quot;react&quot;;<br>import { useGetUserData } from &quot;./useGetUserData&quot;;<br>import { Loader } from &quot;./loader&quot;;<br><br>const UserDetails = () =&gt; {<br>  const { userData, isUserDataLoading } = useGetUserData();<br><br>  return (<br>    &lt;div className=&quot;flex items-center justify-center h-screen bg-gray-100&quot;&gt;<br>      {isUserDataLoading ? (<br>        &lt;Loader /&gt;<br>      ) : (<br>        &lt;h6 className=&quot;text-3xl font-bold text-gray-800&quot;&gt;{userData.name}&lt;/h6&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UserDetails;</pre><p>In this example, both gcTime and staleTime are set to one hour, meaning:</p><ul><li>The user data will be cached for <strong>one hour</strong> before being garbage collected.</li><li>The data will be considered fresh for <strong>one hour</strong>, preventing unnecessary refetching.</li><li>If multiple components use this hook within the hour, they will retrieve data from the cache instead of making redundant API requests.</li><li>React Query manages caching using the queryKey:[“get-user-data”], reducing the need for additional state management solutions like Redux or Context.</li></ul><p>By leveraging React Query’s caching and state management capabilities, we can optimise performance and minimise network requests efficiently.</p><p><strong>Now you will have two questions:</strong></p><p><strong>1. What will Happen After 1 Hour?</strong></p><p>After 1 hour, when the cache expires, React Query will make an actual network request instead of retrieving data from the cache. This ensures that the latest data is fetched and stored in the cache, restarting a new 1-hour cycle.</p><p><strong>2. What if there is need to fetch fresh data, like need of fresh data after updating user profile ?</strong></p><p>let’s discuss below:</p><h3>💡<strong>Fetching Fresh Data Using </strong>refetch()</h3><p>Sometimes, we need to fetch fresh data before the cache expires, such as after updating a user profile. React Query provides a refetch method that forces a new network request, updating the cached data immediately.</p><pre>const { userData, getUserData } = useGetUserData();<br>const getFreshUserData = () =&gt; {<br>  getUserData(); // Force fresh data fetch<br>};</pre><p>In the above hook, we have returned getUserData, which is assigned the refetch method from useQuery. By calling getUserData(), React Query bypasses the cache and makes a new network request to fetch the latest data. This ensures that even if cached data is available, the user receives up-to-date information.</p><h3>🏁 Summary</h3><p>So next time whenever you fetch data using React Query, make sure you define queryKey and add time interval to gcTime and staleTime as per your need, cache the data, reduce network request and reduce dependency on any state management system, keep the code simple and make your app more fast and efficient 🚀</p><p>Other than this, if you have any doubts or suggestions please do put them in the comments.</p><p><strong>🤝Happy coding!</strong></p><p><strong>Thanks for reading!</strong><br>If you found this helpful, let’s connect: 🔗 <a href="https://www.linkedin.com/in/manish-giri-goswami-0b41a1175">LinkedIn</a> | 💻 <a href="https://github.com/manishgcodes">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=868291494d40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IndexedDB with React Hooks: Complete Guide to Client-Side Data Storage]]></title>
            <link>https://manishgcodes.medium.com/effortless-client-side-storage-using-indexeddb-with-react-hooks-0719fdc10d33?source=rss-992c8eff52fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/0719fdc10d33</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[client-side-storage]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[indexeddb]]></category>
            <dc:creator><![CDATA[Manish Giri Goswami]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 12:47:10 GMT</pubDate>
            <atom:updated>2025-11-19T09:51:46.037Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>👨🏻‍💻 Hello Devs,<br></strong>Are you curious about client-side storage options? Today, let’s dive into a powerful tool called IndexedDB. If you’re a beginner in web development, you might wonder, “Is it a conventional database? Do we need to write queries? Can it replace the back-end?” Hold on — let’s clarify things first.</p><p>IndexedDB is a fully functional database available on the client side (browser). However, it is not meant to replace the back-end. So, relax and let’s explore more about it below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ZcOd2gnmaBcyN5sb" /></figure><h3>🤔 What is use of IndexedDB ?</h3><p>Understanding the need or purpose of a tool is essential before learning about it. Let’s discuss a popular use case for IndexedDB. Imagine you’re building a chat application. Users will be texting and sharing messages through a server using APIs or Sockets while online. But what about accessing previous messages and chat data when offline? This is where IndexedDB comes into play.</p><p>In many popular chat applications, we can access profile data and previous messages even when offline. This is possible because the data is pre-stored in IndexedDB while the user is online and allowing access later, even without an internet connection.</p><h3>🤔 What is IndexedDB ?</h3><p>Now that we know why we need it, let’s discuss what it is ?</p><p>Here is a IndexedDB definition generated by ChatGpt 😅<br>“<em>IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files and blobs. It allows for the creation, storage, and querying of databases within a user’s browser. IndexedDB is transactional and provides an asynchronous, non-blocking interface. It is particularly useful for applications that need to store large amounts of data on the client side and need to search and query this data efficiently.</em>”</p><p>In simpler terms, IndexedDB is a storage facility available on the client side (browser) that stores large amounts of structured data, making it easily accessible. The data can be of any type, whether primitive or non-primitive. IndexedDB is like an SQL-based Relational Database Management System (RDBMS). However, unlike SQL-based RDBMSes, which use fixed-column tables, It is a JavaScript-based object-oriented database. It lets us store and retrieve objects that are indexed with a key, any objects supported by the structured clone algorithm can be stored.</p><h3>🚀 Features provided by IndexedDB</h3><p>To fully utilise any tool, we must understand its features. IndexedDB is easy and convenient to use if we understand its features and operations. Unlike other client-side storage options like localStorage, It supports storing complex data types, including objects, arrays, files, and blobs.</p><p>✔️ Its operations are transactional, ensuring data integrity. All read/write operations are part of a transaction, which is either completed successfully or rolled back in case of an error.</p><p>✔️ It is completely Asynchronous in nature, which means it never blocks the main thread and let us maintain the responsive user interface.</p><p>✔️ It allows creating indexes to enable efficient searching and querying of the data.</p><p>✔️ Data is stored in key-value pairs, where each data entry is uniquely identified by a key.</p><p>✔️<strong> </strong>Its transactions are ACID-compliant, ensuring that operations are Atomic, Consistent, Isolated, and Durable.</p><p>✔️ Databases in IndexedDB are versioned. Each change to the database schema requires a new version, allowing for controlled upgrades and schema management.</p><p>✔️<strong> </strong>It uses an event-driven model, where operations are initiated by dispatching events and then handling the corresponding event callbacks.</p><p>✔️<strong> </strong>It is supported by all modern browsers, ensuring wide compatibility for web applications.</p><p>These features make IndexedDB a versatile and robust solution for client-side data storage in web applications.</p><h3>🎯 Finally how to use IndexedDB ?</h3><p>We can find many code snippets or examples for using IndexedDB, but what if I told you that we can manage the entire IndexedDB with a ReactJS hook? Yes, it is possible. We can manage the entire IndexedDB and all its operations by creating a simple custom ReactJS hook, I have successfully used this method in one of my projects at <a href="https://www.webelight.co.in/"><strong>Webelight Solutions</strong></a>.</p><p>You can find a working demonstration of IndexedDB managed using a custom hook in this public <a href="https://github.com/manishgcodes/example-indexed-db"><strong>GitHub Repository</strong></a>. This repository demonstrates how to use IndexedDB in a React application to manage and persist data locally. The project is created using Vite for a fast and optimized development environment. In this repository, I shared the simplest method I know. I hope that once you try it, you’ll also find it easy and precise.</p><p>For your understanding, I am explaining the code blocks step by step from the custom hook below.</p><p><strong>Step 1. We have to open a connection with IndexedDB 🕵</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*e6J_cl7nlPZ0eQhqusI28g.png" /></figure><p>In the above example you can simply understand that we opened the connection with indexedDB, and named it “<em>test-db</em>” and provided version “<em>0.1</em>”.</p><p>It check if any instance of DB is already present with the given name and version then it connects with it and if not then it creates the new database with the given name and version,</p><p>Later on we initialised the request const with connection and, created the tables, while checking if the tables are not previously present, in case if the DB is connected to the existing DB</p><p>After successfully connecting with IndexedDB, you will be able to find the database and table in the dev tools of your browser in storage section of Application tab👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*G6dWOJkrxO8-FLwcdmkG1Q.png" /></figure><p><strong>Step 2. Then we create a function to get transaction</strong>👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*n2sMGQtmA1cRuz9aXw8s2w.png" /><figcaption>Add this function below useEffect hook, getTransaction function will be used by rest of the function we will be adding in next steps</figcaption></figure><p><strong>Step 3. Then this is how we can insert or update a single indexed data</strong>👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*tXNTPygITSVTn8PgIiA_sg.png" /><figcaption>Add this code below useEffect hook in useIndexedDB hook shown in 1st step and return from it.</figcaption></figure><p>After adding the data in IndexedDB use the refresh button and than the record will look like this👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*nMvbU8ZkWhR3VQTDsEYVVg.png" /></figure><p><strong>Step 4. This is how we can get data</strong>👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*NcBiB6CqE-27R1uh6YvzsA.png" /><figcaption>Add this function below useEffect hook in useIndexedDB hook shown in 1st step and return from it.</figcaption></figure><p><strong>Step 5. This is how we can delete data</strong>👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*zPB3coz6Q2hToLUROSZ82Q.png" /><figcaption>Add this function below useEffect hook in useIndexedDB hook shown in 1st step and return from it.</figcaption></figure><p>Similarly, I have also created methods for storing and retrieving bulk data in IndexedDB. The code blocks shared above are from a custom hook that I created to manage IndexedDB and all its operations. You can find all of this in this <a href="https://github.com/manishgcodes/example-indexed-db"><strong>Github Repository</strong></a><strong>.</strong></p><h3>🏁 Summary</h3><p>IndexedDB is a powerful client-side database that allows for efficient storage and retrieval of large amounts of structured data directly in the browser. By integrating IndexedDB with ReactJS through custom hooks, we can seamlessly manage database operations such as connecting, inserting, updating, and deleting data. This approach not only simplifies the code but also enhances the performance and responsiveness of our web applications. For a practical demonstration and to explore the full capabilities of IndexedDB check out the linked <a href="https://github.com/manishgcodes/example-indexed-db"><strong>GitHub repository</strong></a>.</p><p><strong>🌐Visit: </strong><a href="https://github.com/manishgcodes/example-indexed-db">https://github.com/manishgcodes/example-indexed-db</a></p><h4>🤝<strong>Happy coding!</strong></h4><p><strong>Thanks for reading!</strong><br>If you found this helpful, let’s connect: 🔗 <a href="https://www.linkedin.com/in/manish-giri-goswami-0b41a1175">LinkedIn</a> | 💻 <a href="https://github.com/manishgcodes">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0719fdc10d33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>