Reduce redundant refetches
Data changes occasionally and short-term cached reads are acceptable.
TanStack · Pipe
staleTime defines how long cached query data stays fresh. Increasing it reduces stale-driven refetches; Infinity waits for manual invalidation, while 'static' prevents even that from triggering a refetch.
staleTime controls how long query data remains fresh after it is received. During that window, the cache can satisfy reads without stale-driven refetches; once it expires, normal background refetch triggers can apply. Infinity prevents staleness until manual invalidation, while 'static' also prevents manual invalidation from triggering a refetch.
staleTime: number | "static" | ((query: Query<TQueryFnData, TError, TQueryData, TQueryKey>) => number | "static")| Name | Type | Description |
|---|---|---|
staleTime | number | "static" | ((query) => number | "static") | Freshness duration in milliseconds, or the special value 'static'. A function form can compute the value from the query. |
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'
const queryClient = new QueryClient({
defaultOptions: {
queries: { staleTime: 2 * 60 * 1000 },
},
})
function Todos() {
const { data } = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('/api/todos').then((r) => r.json()),
})
return <pre>{JSON.stringify(data, null, 2)}</pre>
}
export function App() {
return <QueryClientProvider client={queryClient}><Todos /></QueryClientProvider>
}Sets a two-minute freshness window globally, so cached todo data is reused during that period without stale-driven refetches.
Data changes occasionally and short-term cached reads are acceptable.
Data is immutable for the lifetime of the running application.
Data should remain fresh until an explicit application event invalidates it.
staleTime is the duration, in milliseconds, for which fetched data is treated as fresh. A longer value reduces stale-driven refetches, while the default behavior treats cached data as stale.
Follow-up: How would you keep boot-time reference data from refetching? Use 'static' when it cannot change during the app session; use Infinity if manual invalidation should remain effective.
A query with staleTime: Infinity does not become stale automatically, so it avoids refetches caused by staleness. Manual invalidation can still invalidate it and allow a refetch.
Follow-up: What is the stricter alternative? staleTime: 'static', which remains non-refetching even after manual invalidation.
staleTime is separate from refetchInterval. An interval can periodically refetch a query regardless of whether staleTime has elapsed.
Follow-up: Which other events can refetch stale queries? New mounts, window refocus, and network reconnection, unless their refetch options are customized.
QueryClientQueryObserverOptionsrefetchIntervalrefetchOnMountrefetchOnWindowFocusrefetchOnReconnectinvalidateQueries