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
⚡ The Problem
// 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
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.
Understand staleTime: 0 Is the Default
Root cause — data immediately stale after every fetchThe 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.
// ❌ 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 triggerstaleTime 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.
Set staleTime Globally on QueryClient
Apply consistent caching across all queriesRather than adding staleTime to every useQuery call, set a sensible global default. Individual queries can override it as needed.
"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>
)
}// 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
})Disable refetchOnWindowFocus
Query refetches every time you switch browser tabsBy 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.
// 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
})Understand staleTime vs gcTime (cacheTime)
Confusion between these two optionsThese 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.
// 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 againgcTime 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.
Per-Query staleTime for Fine-Grained Control
Different data types need different freshness windowsA well-architected app uses different staleTime values based on how frequently the underlying data changes. Use custom hooks to encapsulate these settings.
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
- Never rely on the default staleTime: 0 in production — set a meaningful global default on QueryClient
- Use staleTime: Infinity for static data (config, categories, countries) and invalidate manually after mutations
- Keep refetchOnWindowFocus: true but use staleTime to control how frequently it actually fires
- Set gcTime longer than staleTime so users see cached data instantly while a refetch happens in background
- Rename cacheTime to gcTime if upgrading from TanStack Query v4 to v5
- Encapsulate staleTime per data type in custom hooks — makes freshness requirements explicit and consistent
Frequently Asked Questions
What is staleTime in TanStack Query?+−
Why does my query refetch every time even with staleTime set?+−
What is the difference between staleTime and gcTime?+−
Should I set a global staleTime or per-query?+−
Can staleTime be Infinity?+−
Does staleTime affect the initial fetch?+−
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