Tune inactive-cache retention
Retain query results for a controlled period after a component unmounts.
TanStack · Pipe
gcTime specifies how long unused or inactive TanStack Query cache data stays in memory before garbage collection. It defaults to five minutes, is Infinity during SSR, and can be set to Infinity to disable collection.
gcTime controls how long inactive query data remains in memory after the query has no subscribers. Once that period expires, TanStack Query garbage-collects the data; it does not limit retention while the query is actively used. The longest configured duration applies, Infinity disables collection, and SSR defaults to Infinity.
gcTime?: number| Name | Type | Description |
|---|---|---|
gcTime | number | undefined | Retention duration, in milliseconds, for unused or inactive query cache data. |
import { QueryClient, useQuery } from '@tanstack/react-query'
const queryClient = new QueryClient({
defaultOptions: {
queries: { gcTime: 1000 * 60 * 60 * 24 },
},
})
export function Todos() {
const query = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('/api/todos').then((r) => r.json()),
gcTime: 1000 * 60 * 5,
})
return <pre>{JSON.stringify(query.data)}</pre>
}This query keeps unused data for five minutes, while the client default retains other query data for one day.
Retain query results for a controlled period after a component unmounts.
Keep hydrated or persisted data available long enough for the persistence policy.
Prevent automatic removal of inactive data in a long-lived client.
gcTime is the retention period for unused or inactive query data. It begins to matter only after a query is no longer in use; expiration then allows the cached data to be garbage-collected.
Follow-up: How does it interact with multiple configurations? The longest specified garbage-collection duration is used.
The default is five minutes in normal operation and Infinity during SSR. Setting gcTime to Infinity disables garbage collection, so inactive data is not automatically removed.
Follow-up: What value should be used with persisted queries? Set gcTime to the same value or higher than the persistence maxAge.
gcTime is distinct from staleTime. staleTime determines when data becomes stale, whereas gcTime determines how long unused data remains in memory before collection.
Follow-up: What limits unusually long gcTime values? The ordinary timer implementation supports roughly 24 days; timeoutManager.setTimeoutProvider can provide a workaround.
staleTimeQueryClientdefaultOptions.queriespersistQueryClienttimeoutManager.setTimeoutProvider