TanStack QueryReact QueryError Fix2026 Updated

TanStack Query staleTime Not Working— Query Refetches Every Mount [Fixed 2026]

Also covers: staleTime: 0 default · global QueryClient config · refetchOnWindowFocus · gcTime vs staleTime · Infinity staleTime

January 20266 min readTanStack Query v5 · React · TypeScript

⚡ The Problem

Error
// Query refetches every time component mounts — even with staleTime set
const { data } = useQuery({
  queryKey: ["products"],
  queryFn: fetchProducts,
  staleTime: 5 * 60 * 1000,  // 5 minutes — but it still refetches!
})

✅ Fastest Fix — check refetchOnWindowFocus and global defaults

Set global staleTime + disable window focus refetch
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60 * 1000,          // 1 minute global default
      refetchOnWindowFocus: false,   // stop refetch on tab switch
    },
  },
})

Why staleTime Appears to Be Ignored

TanStack Query has three triggers that cause a refetch: component mount, window focus, and network reconnect. staleTime only prevents a refetch if data is still fresh at the moment a trigger fires. If the staleTime window has expired (or is 0 by default), all three triggers will cause a background refetch. Understanding which trigger is firing is the key to fixing unexpected refetches.

1

Understand staleTime: 0 Is the Default

Root cause — data immediately stale after every fetch
2 min

The TanStack Query default is staleTime: 0, meaning data is considered stale the instant it arrives. Every mount, window focus, and reconnect will trigger a background refetch. You must explicitly set staleTime to prevent this.

The three refetch triggers and how staleTime affects each
// ❌ Default behaviour — staleTime: 0 means data always stale
const { data } = useQuery({ queryKey: ["posts"], queryFn: fetchPosts })
// Refetches on: component mount ✅, window focus ✅, network reconnect ✅

// ✅ With staleTime — data fresh for 5 minutes
const { data } = useQuery({
  queryKey: ["posts"],
  queryFn: fetchPosts,
  staleTime: 5 * 60 * 1000,  // 5 minutes in ms
})
// During staleTime window: NO background refetch on mount or focus
// After staleTime expires: refetches again on next trigger

staleTime does NOT prevent showing cached data — it only prevents background refetches. Even with staleTime: 0, cached data is shown instantly while the refetch happens in the background. This is what makes TanStack Query feel fast.

2

Set staleTime Globally on QueryClient

Apply consistent caching across all queries
3 min

Rather than adding staleTime to every useQuery call, set a sensible global default. Individual queries can override it as needed.

providers/query-provider.tsx
"use client"

import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { ReactQueryDevtools } from "@tanstack/react-query-devtools"
import { useState } from "react"

export function QueryProvider({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () => new QueryClient({
      defaultOptions: {
        queries: {
          staleTime: 60 * 1000,            // 1 minute — good default for most data
          gcTime: 5 * 60 * 1000,           // 5 minutes in memory after unmount
          refetchOnWindowFocus: true,      // keep true — staleTime controls whether it fires
          refetchOnReconnect: true,
          retry: 1,
        },
      },
    })
  )

  return (
    <QueryClientProvider client={queryClient}>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  )
}
Per-query overrides — different data needs different freshness
// Static data — config, categories, countries
const { data: categories } = useQuery({
  queryKey: ["categories"],
  queryFn: fetchCategories,
  staleTime: Infinity,           // never refetch unless manually invalidated
})

// Semi-static — blog posts, products
const { data: posts } = useQuery({
  queryKey: ["posts"],
  queryFn: fetchPosts,
  staleTime: 5 * 60 * 1000,     // 5 minutes
})

// Real-time — prices, stock, live scores
const { data: price } = useQuery({
  queryKey: ["price", ticker],
  queryFn: () => fetchPrice(ticker),
  staleTime: 0,                  // always stale — refetch every trigger
  refetchInterval: 10_000,       // also poll every 10 seconds
})
3

Disable refetchOnWindowFocus

Query refetches every time you switch browser tabs
2 min

By default, TanStack Query refetches stale queries when the browser window regains focus. This is useful for keeping dashboards fresh, but annoying for static data. Disable it globally or per-query.

Disable window focus refetch
// Option A — disable globally (simpler, loses dashboard freshness)
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60 * 1000,
      refetchOnWindowFocus: false,   // ← no refetch on tab switch
    },
  },
})

// Option B — disable per-query (more granular)
const { data } = useQuery({
  queryKey: ["config"],
  queryFn: fetchConfig,
  staleTime: Infinity,
  refetchOnWindowFocus: false,     // override just for this query
})

// Option C — keep window focus but control via staleTime
// If staleTime is 5 minutes, window focus only triggers refetch AFTER 5 mins
// This is the recommended approach — set a meaningful staleTime and keep focus on
const { data } = useQuery({
  queryKey: ["dashboard"],
  queryFn: fetchDashboard,
  staleTime: 30 * 1000,            // 30 seconds — refetches on focus after 30s
  refetchOnWindowFocus: true,      // keep enabled — staleTime does the limiting
})
4

Understand staleTime vs gcTime (cacheTime)

Confusion between these two options
3 min

These two options control different things. staleTime controls freshness (when to refetch). gcTime controls memory (when to remove from cache). Getting them confused leads to unexpected behaviour.

staleTime vs gcTime — visual model
// Timeline after a successful fetch:
//
// t=0s      Data fetched ← fresh (no background refetch triggered)
// t=60s     staleTime expires ← data is now STALE
//           Next mount/focus/reconnect WILL trigger background refetch
// t=300s    gcTime expires ← query removed from cache if no subscribers
//           Next mount will show loading (no cached data)

const { data } = useQuery({
  queryKey: ["posts"],
  queryFn: fetchPosts,
  staleTime: 60 * 1000,     // fresh for 1 minute
  gcTime: 5 * 60 * 1000,    // stay in cache for 5 minutes after no subscribers
})

// ✅ Common pattern: gcTime > staleTime
// Data becomes stale → triggers background refetch on next trigger
// But cached (stale) data shows instantly while refetch happens
// After gcTime: cache cleared → next mount shows loading state again

gcTime was called cacheTime in TanStack Query v4. If you are upgrading from v4, rename cacheTime to gcTime in all your query options. The default gcTime is 5 minutes.

5

Per-Query staleTime for Fine-Grained Control

Different data types need different freshness windows
3 min

A well-architected app uses different staleTime values based on how frequently the underlying data changes. Use custom hooks to encapsulate these settings.

hooks — encapsulate staleTime per data type
import { useQuery } from "@tanstack/react-query"

// Static data — app config, feature flags, categories
export function useConfig() {
  return useQuery({
    queryKey: ["config"],
    queryFn: () => fetch("/api/config").then(r => r.json()),
    staleTime: Infinity,           // never background-refetch
    gcTime: Infinity,              // keep in memory forever
  })
}

// User-owned data — changes when user edits
export function useUserProfile(userId: string) {
  return useQuery({
    queryKey: ["profile", userId],
    queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()),
    staleTime: 5 * 60 * 1000,     // 5 minutes
    enabled: !!userId,
  })
}

// Volatile data — changes frequently without user action
export function useStockPrice(ticker: string) {
  return useQuery({
    queryKey: ["stock", ticker],
    queryFn: () => fetch(`/api/stocks/${ticker}`).then(r => r.json()),
    staleTime: 0,                  // always stale
    refetchInterval: 15_000,       // poll every 15 seconds
    refetchIntervalInBackground: false,
  })
}

Prevention

Frequently Asked Questions

What is staleTime in TanStack Query?+
staleTime is the duration in milliseconds that fetched data is considered fresh. While data is fresh, TanStack Query will not re-fetch it in the background, even if the component remounts or the window is refocused. The default is 0, meaning data is immediately stale after fetching and will refetch on every trigger.
Why does my query refetch every time even with staleTime set?+
The most common cause is that staleTime is set correctly but refetchOnWindowFocus is also triggering. When you switch tabs and return, TanStack Query refetches stale queries by default. If your staleTime has already expired, the refetch is valid. Set refetchOnWindowFocus: false to disable this behaviour.
What is the difference between staleTime and gcTime?+
staleTime controls when data is considered stale and triggers a background refetch. gcTime (formerly cacheTime in v4) controls how long unused cached data stays in memory before being garbage collected. A query can be stale but still have cached data — it will show the cached data immediately while refetching in the background.
Should I set a global staleTime or per-query?+
Set a sensible global default on QueryClient (e.g. 60 seconds) and override per-query for data with different freshness requirements. Static data like config or categories can have Infinity staleTime; real-time data like prices can have 0 or a short staleTime.
Can staleTime be Infinity?+
Yes. staleTime: Infinity means data never becomes stale and will never be refetched in the background. You must manually invalidate the query with queryClient.invalidateQueries() to trigger a refetch. Useful for data that only changes when you explicitly mutate it.
Does staleTime affect the initial fetch?+
No. staleTime only applies after the first successful fetch. On the very first render when there is no cached data, the query always fetches regardless of staleTime. staleTime controls subsequent background refetches, not the initial load.

Need Expert Help?

We Build React Apps with TanStack Query

Softplix engineers architect data-fetching layers with TanStack Query — caching, mutations, optimistic updates, and SSR hydration. Let us help.

Talk to an Engineer