← Back to the journal

5 Things Your React Query Cache Is Doing Without You Realising

Your data is already in memory, your component looks perfectly healthy, and yet another request appears in the Network tab. Understanding React Query's defaults can save hours of debugging.

On this page

5 Things Your React Query Cache Is Doing Without You Realising

Reading position1 / 7
Editorial illustration for 5 Things Your React Query Cache Is Doing Without You Realising
AI-generated editorial illustration

You open a product page, navigate away, then return. The products appear instantly. That's what you expected from a cache.

But the Network tab tells a slightly different story: another request has just gone to /api/products.

Later, you switch to another browser tab and return. Another request. A temporary server error produces several more. And when you update a product, the list and detail views don't necessarily agree.

None of these behaviours automatically means something is broken. TanStack Query (formerly React Query) is doing more than storing responses. It manages freshness, subscriptions, background updates, failures and the lifetime of data.

The trick is understanding which part of that machinery is responsible before changing the configuration.

This article uses the React adapter of TanStack Query v5 and its browser-side defaults. Older examples often refer to cacheTime; in v5 the option is called gcTime.

1. Your cached data can be stale the moment it arrives

Consider a fairly ordinary query:

import { useQuery } from '@tanstack/react-query';

async function getProducts({ signal }) {
  const response = await fetch('/api/products', { signal });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

function ProductList() {
  const { data, isPending, isError, isFetching } = useQuery({
    queryKey: ['products'],
    queryFn: getProducts,
  });

  if (isPending) return <p>Loading products…</p>;
  if (isError && !data) return <p>Unable to load products.</p>;

  return (
    <section>
      {isFetching && <small>Refreshing…</small>}
      {isError && <p>Refresh failed. Showing previous data.</p>}
      {data.map(product => <p key={product.id}>{product.name}</p>)}
    </section>
  );
}

By default, staleTime is zero. A successful response is stored, but it is immediately eligible for revalidation. That sounds contradictory until you distinguish having data from trusting its freshness.

Stale does not mean unusable. Nor does it mean a request must start the instant the data becomes stale. It means that when an appropriate refetch trigger occurs, the library can request a newer version.

If your product catalogue changes infrequently, you could express that explicitly:

useQuery({
  queryKey: ['products'],
  queryFn: getProducts,
  staleTime: 60_000,
});

For a minute after a successful data update, this observer considers the result fresh. Ordinary mount, focus and reconnect triggers no longer need to refresh that fresh result. Manual refetches, invalidation and configured polling are separate mechanisms.

Notice what we didn't change: the endpoint, database, or response format. We simply told the client how much freshness the screen needs.

Figure 1 — Freshness and retention are separate clocks.

Article illustration
SVG source
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="245" viewBox="0 0 760 245" role="img" aria-label="Two independent cache clocks">
<rect width="760" height="245" rx="8" fill="#f6f4ee"/>
<text x="24" y="34" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">Two independent cache clocks</text>
<text x="24" y="65" font-family="Arial, sans-serif" font-size="14" fill="#6d7268" text-anchor="start">Data freshness: 60 seconds</text>
<rect x="24" y="78" width="280" height="38" rx="6" fill="#e6eadd" stroke="#242b25"/>
<rect x="304" y="78" width="432" height="38" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="164" y="102" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Fresh</text>
<text x="520" y="102" font-family="Arial, sans-serif" font-size="14" fill="#6d7268" text-anchor="middle">Stale — data still available</text>
<text x="24" y="137" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="start">0s</text>
<text x="304" y="137" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="middle">60s</text>
<text x="24" y="166" font-family="Arial, sans-serif" font-size="14" fill="#6d7268" text-anchor="start">Unused retention: 600 seconds from last observer leaving</text>
<rect x="117" y="178" width="619" height="35" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="426" y="200" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Unused cache retained</text>
<text x="117" y="231" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="middle">20s: unmount</text>
<text x="736" y="231" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="end">620s: GC</text>
</svg>
Download SVG

A catalogue and a live inventory counter probably shouldn't have identical freshness policies. A long stale time on a catalogue may be acceptable; the server must still validate stock and price when a customer checks out. Cached data is not an authorization or transaction guarantee.

2. Your cache is refreshing data while you are doing something else

A developer reports that a request seems to happen every time they inspect their application. They disable Strict Mode, add a useRef, and start questioning whether a component is mounting twice.

Sometimes the explanation is simpler: they switched away from the page and returned to it.

With the usual defaults, stale queries may refetch when an observer mounts, the page regains focus (in v5, browser visibility changes are used by default), or a network connection returns. This is useful. Someone returning to a dashboard after lunch probably wants more recent information than the data they saw in the morning.

The confusing part is that cached data may remain visible during the fetch. A successful query can be fetching again. Those two facts do not conflict.

SituationstatusfetchStatus
First request running, no datapendingfetching
Successful data, no current requestsuccessidle
Background refresh of successful datasuccessfetching
Initial request waiting for connectivitypendingpaused

These are representative states, not every possible combination. A failed background refresh can also leave previous data available.

Avoid replacing an entire page with a spinner whenever isFetching is true. Reserve a full loading state for the initial fetch (isPending alone can also describe disabled or paused queries). Keep the previous results visible and show a small updating indicator during a background refresh.

Figure 2 — The background refresh does not need to blank the page.

Article illustration
SVG source
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="235" viewBox="0 0 760 235" role="img" aria-label="Keep the existing data visible">
<rect width="760" height="235" rx="8" fill="#f6f4ee"/>
<text x="24" y="34" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">Keep the existing data visible</text>
<text x="24" y="65" font-family="Arial, sans-serif" font-size="14" fill="#6d7268" text-anchor="start">Initial load</text>
<rect x="24" y="78" width="220" height="53" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="134" y="110" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle">Loading…</text>
<line x1="244" y1="104" x2="270" y2="104" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="270,104 262,100 262,108" fill="#6d7268"/>
<rect x="270" y="78" width="220" height="53" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="380" y="110" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle">Products visible</text>
<line x1="490" y1="104" x2="516" y2="104" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="516,104 508,100 508,108" fill="#6d7268"/>
<rect x="516" y="78" width="220" height="53" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="626" y="110" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle">Products visible</text>
<text x="626" y="151" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="middle">Refreshing in background</text>
<line x1="24" y1="174" x2="736" y2="174" stroke="#d9ddd2" stroke-width="1.5"/>
<text x="380" y="202" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle">A successful query can be fetching again.</text>
</svg>
Download SVG

Sometimes a particular screen should not refresh on visibility changes:

useQuery({
  queryKey: ['report', reportId],
  queryFn: ({ signal }) => fetchReport(reportId, signal),
  staleTime: 5 * 60_000,
  refetchOnWindowFocus: false,
});

This is a policy decision, not a universal optimization. Turning off every automatic trigger across an application can make old data surprisingly persistent.

Also, refetchInterval is independent of freshness. A query with a five-minute stale time can still poll every ten seconds if you explicitly configure it that way. Inspect the effective options before blaming the cache.

3. An unused query can survive long after its component disappears

Suppose you visit a product detail page and then navigate back to the catalogue. The last observer of the detail query unmounts.

Does the cached detail disappear? Usually not.

The default browser gcTime is five minutes. Once a query becomes unused, its garbage-collection timer determines when that entry can be removed. Returning before that happens can reuse its existing data. If the data is stale, it can also initiate a refresh.

Try this configuration:

useQuery({
  queryKey: ['product', productId],
  queryFn: ({ signal }) => fetchProduct(productId, signal),
  staleTime: 60_000,
  gcTime: 10 * 60_000,
});

Imagine the request succeeds at 0 seconds and the last observer disappears at 20 seconds. At 60 seconds, the data becomes stale. At 620 seconds, the unused query can be collected, assuming it remains unused and no fetch is keeping it around.

Freshness runs from the data update. Retention runs from inactivity. If the query is observed continuously, the unused-cache timer does not discard it merely because ten minutes have passed.

The reverse case is interesting too. A query with a one-hour stale time and a five-minute garbage-collection time can be removed while its data would otherwise still be fresh. Returning to the screen after removal requires another load.

This matters for search interfaces. Every distinct search term can create another entry:

queryKey: ['search', { term, page, accountId }]

A long retention period may improve back-navigation but increase memory usage as users explore hundreds of combinations. Query data can be considerably larger than its key. gcTime is not a byte limit or an LRU cache size.

For short-lived search results, consider a shorter gcTime and measure the number and size of cached queries. For costly reports that users frequently revisit, a longer retention window may be worthwhile.

On logout, clear the session-specific cache and ensure authentication transitions cannot reuse the previous user's data. Scope keys to the actual account or tenant, and isolate server-side query clients by request. Never put raw credentials in query keys.

4. One failed query can mean four network attempts

You call an endpoint once. It returns an error. Then your application waits, tries again, waits longer and tries again.

On the browser, a failed query normally receives up to three retries by default. That's one original attempt and three additional attempts, not three attempts in total. The standard delay increases exponentially from about one second and is capped at thirty seconds. Server-side defaults differ: retries are disabled by default there.

Figure 3 — One logical query, four attempts.

Article illustration
SVG source
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="207" viewBox="0 0 760 207" role="img" aria-label="One logical query, four attempts">
<rect width="760" height="207" rx="8" fill="#f6f4ee"/>
<text x="24" y="34" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">One logical query, four attempts</text>
<text x="24" y="64" font-family="Arial, sans-serif" font-size="13" fill="#6d7268" text-anchor="start">Illustrative delays, ignoring request duration</text>
<rect x="24" y="102" width="116" height="47" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="82" y="130" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Initial</text>
<rect x="150" y="102" width="116" height="47" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="208" y="130" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Retry 1</text>
<rect x="320" y="102" width="116" height="47" rx="6" fill="#fffef9" stroke="#d9ddd2"/>
<text x="378" y="130" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Retry 2</text>
<rect x="606" y="102" width="116" height="47" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="664" y="130" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">Retry 3</text>
<line x1="140" y1="125" x2="150" y2="125" stroke="#6d7268" stroke-width="1.5"/>
<text x="145.0" y="90" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="middle">1s</text>
<line x1="266" y1="125" x2="320" y2="125" stroke="#6d7268" stroke-width="1.5"/>
<text x="293.0" y="90" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="middle">2s</text>
<line x1="436" y1="125" x2="606" y2="125" stroke="#6d7268" stroke-width="1.5"/>
<text x="521.0" y="90" font-family="Arial, sans-serif" font-size="12" fill="#6d7268" text-anchor="middle">4s</text>
<text x="24" y="182" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="start">Four attempts at most with the standard browser retry count.</text>
</svg>
Download SVG

This can explain why a failure message takes longer to appear than expected. It can also hide temporary service failures from application-level success metrics.

The important detail: a query function must reject or throw for TanStack Query to recognize failure. Native fetch() does not reject just because the response has a 404 or 500 status.

A more selective policy might look like this:

class HttpError extends Error {
  constructor(status) {
    super(`HTTP ${status}`);
    this.status = status;
  }
}

async function fetchJSON(url, signal) {
  const response = await fetch(url, { signal });
  if (!response.ok) throw new HttpError(response.status);
  return response.json();
}

function retryRead(failureCount, error) {
  if (failureCount >= 2) return false;
  if (error instanceof HttpError) {
    return [408, 500, 502, 503, 504].includes(error.status);
  }
  return false;
}

const productQuery = id => ({
  queryKey: ['product', id],
  queryFn: ({ signal }) => fetchJSON(`/api/products/${encodeURIComponent(id)}`, signal),
  retry: retryRead,
});

This deliberately conservative policy permits two retries for selected HTTP failures and does not automatically retry parsing errors, cancellations or ambiguous network exceptions. Real clients may classify transient network errors more precisely. For 429 responses, use a policy that respects the provider's Retry-After header instead of hammering the endpoint.

Don't reuse the same policy indiscriminately for mutations. Sending a payment twice is fundamentally different from reading a product twice. TanStack Query mutations do not retry by default; if you enable retries, design the server operation to tolerate them.

Check whether your HTTP client already retries requests. Two independent retry mechanisms can multiply attempts. Our earlier article, Why Retrying Failed API Requests Can Make Things Worse, explores that problem in more detail.

Imagine a server returning this data twice:

const before = {
  products: [{ id: 1, name: 'Keyboard' }, { id: 2, name: 'Mouse' }],
};

const after = {
  products: [{ id: 1, name: 'Keyboard' }, { id: 2, name: 'Wireless Mouse' }],
};

Parsing the second response normally produces entirely new object references. TanStack Query's structural sharing can retain unchanged references between JSON-compatible responses. In this example, the unchanged keyboard object can keep its previous identity even though the response root changes.

That is useful for memoized children and derived data. It is not a guarantee that a React component will never render again. Parent rendering, local state, context and query metadata can still trigger renders.

The library also tracks which query-result properties a component reads. A component using only data need not be notified solely because isFetching changed. Object rest destructuring can defeat that optimization:

// Reads the remaining properties as well.
const { data, ...metadata } = useQuery(options);

// Prefer the fields the component actually needs.
const { data, isPending } = useQuery(options);

For a small widget, select the relevant slice rather than subscribe to an entire response:

const selectCount = products => products.length;

function useProductCount() {
  return useQuery({
    queryKey: ['products'],
    queryFn: getProducts,
    select: selectCount,
  });
}

select changes the observer's returned data, not the underlying cache entry. Keeping a selector stable can avoid unnecessary recalculation. Do not mutate cached data in place; return new objects when updating it.

There is another limit worth understanding. Query caches are keyed by resource identity, not automatically normalized into a single entity database.

['products']
['product', 123]

Both may contain product 123, but changing the detail entry does not automatically rewrite every list containing that product.

After a successful mutation, update the exact detail response if the server returned a complete authoritative record, then invalidate affected lists:

import { useMutation, useQueryClient } from '@tanstack/react-query';

function useUpdateProduct(id) {
  const client = useQueryClient();

  return useMutation({
    mutationFn: async changes => {
      const response = await fetch(`/api/products/${encodeURIComponent(id)}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(changes),
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return response.json();
    },
    onSuccess: async updated => {
      // Assumes a complete authoritative product in the response.
      client.setQueryData(['product', id], updated);
      await client.invalidateQueries({ queryKey: ['products'] });
    },
  });
}

Invalidating ordinary active queries marks them for refresh by default; inactive matches are generally marked stale for later use. Disabled queries and queries configured with staleTime: 'static' have special behaviour. Infinity is different from 'static': infinite freshness can still be overridden by ordinary invalidation, while static freshness opts out of invalidation-driven refetching in supported v5 versions.

Figure 4 — Two cache entries, one underlying product.

Article illustration
SVG source
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="260" viewBox="0 0 760 260" role="img" aria-label="Separate keys, separate cached responses">
<rect width="760" height="260" rx="8" fill="#f6f4ee"/>
<text x="24" y="34" font-family="Arial, sans-serif" font-size="20" fill="#242b25" text-anchor="start">Separate keys, separate cached responses</text>
<rect x="24" y="77" width="180" height="54" rx="6" fill="#fffef9" stroke="#242b25"/>
<text x="114" y="109" font-family="Arial, sans-serif" font-size="14" fill="#242b25" text-anchor="middle">PATCH product 123</text>
<line x1="204" y1="104" x2="274" y2="104" stroke="#6d7268" stroke-width="1.5"/>
<polygon points="274,104 266,100 266,108" fill="#6d7268"/>
<rect x="274" y="77" width="462" height="54" rx="6" fill="#e6eadd" stroke="#242b25"/>
<text x="505" y="109" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle">Detail: setQueryData</text>
<line x1="114" y1="131" x2="114" y2="181" stroke="#6d7268" stroke-width="1.5"/>
<line x1="114" y1="181" x2="274" y2="181" stroke="#ab4932" stroke-width="1.5"/>
<polygon points="274,181 266,177 266,185" fill="#ab4932"/>
<rect x="274" y="154" width="462" height="54" rx="6" fill="#fffef9" stroke="#ab4932"/>
<text x="505" y="186" font-family="Arial, sans-serif" font-size="15" fill="#242b25" text-anchor="middle">List: invalidateQueries</text>
<text x="380" y="238" font-family="Arial, sans-serif" font-size="14" fill="#6d7268" text-anchor="middle">Refresh related lists rather than assume automatic normalization.</text>
</svg>
Download SVG

In applications with concurrent reads and writes, cancel obsolete fetches where appropriate or use authoritative version checks so a late response cannot overwrite a newer update. The example above is a simple mutation pattern, not a complete optimistic-update protocol.

A practical starting configuration

Instead of tuning every option globally after seeing a surprising network request, set modest defaults and override them for specific resources.

import { useState } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

export function Providers({ children }) {
  const [client] = useState(() => new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 30_000,
        gcTime: 5 * 60_000,
        retry: retryRead,
      },
    },
  }));

  return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
}

This is an illustrative browser provider. Import the retry function from your API module. Keep the client stable across renders; for SSR, follow the framework's request isolation and hydration guidance rather than sharing a server-side singleton among users.

OptionTypical browser default in v5Question to ask
staleTime0How old can this data be before revalidation is useful?
gcTime5 minutesHow long should unused data occupy memory?
retry3Which failures deserve another attempt?
refetchOnWindowFocustrueDoes returning to this screen justify refreshing stale data?
structuralSharingtrueCan unchanged JSON-compatible data retain its references?

When investigating real requests, use the browser Network panel alongside TanStack Query Devtools. Inspect the query key, freshness, observer count and fetch status. Compare development and production builds and distinguish HTTP cache hits from actual server requests. Change one option at a time and repeat the same navigation sequence.

Final thoughts

A cache that never refreshes may look efficient in a network trace, but it can make an application incorrect. A cache that refreshes too eagerly can waste resources without improving the experience.

React Query's defaults make sense once you stop thinking of the cache as a simple map of URLs to responses. Each entry has a lifecycle, and each observer has a policy for how it consumes that entry.

Before disabling another refetch or increasing another timeout, ask which problem you are solving: freshness, retention, failure recovery, or rendering.

The answer often tells you exactly which setting to change.

THE CONVERSATION

Comments

Add your perspective ↓

Questions, useful examples and different approaches are welcome. Keep the discussion thoughtful and on topic.

Loading comments…

    Add your perspective

    All comments are reviewed before publication. Your name and comment will be public after approval; your email stays private and is used for account access or moderation, not a mailing list.

    Checking sign-in…