The QueryClient is the central class in TanStack Query that manages all query and mutation caches. It provides methods to fetch, cache, and synchronize server state.
Constructor
Creates a new QueryClient instance.
const queryClient = new QueryClient ( config ?: QueryClientConfig )
Configuration options for the QueryClient Custom QueryCache instance. If not provided, a new one will be created.
Custom MutationCache instance. If not provided, a new one will be created.
Default options for queries and mutations. Default options for all queries.
Default options for all mutations.
Example
import { QueryClient } from '@tanstack/query-core'
const queryClient = new QueryClient ({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5 , // 5 minutes
gcTime: 1000 * 60 * 10 , // 10 minutes
},
},
})
Methods
fetchQuery
Fetches a query and returns a promise with the data. If the query exists and the data is not stale, it will return the cached data.
fetchQuery < TQueryFnData , TError , TData , TQueryKey >(
options : FetchQueryOptions < TQueryFnData , TError , TData , TQueryKey >
): Promise < TData >
options
FetchQueryOptions
required
Options for fetching the query A unique key for the query.
The function that the query will use to request data.
staleTime
number | ((query: Query) => number)
Time in milliseconds after which data is considered stale.
Returns a promise that resolves with the query data.
Example
const data = await queryClient . fetchQuery ({
queryKey: [ 'todos' ],
queryFn: fetchTodos ,
})
prefetchQuery
Prefetches a query and caches the result. Unlike fetchQuery, it does not return the data and does not throw errors.
prefetchQuery < TQueryFnData , TError , TData , TQueryKey >(
options : FetchQueryOptions < TQueryFnData , TError , TData , TQueryKey >
): Promise < void >
options
FetchQueryOptions
required
Same options as fetchQuery.
Returns a promise that resolves when the query is prefetched.
Example
await queryClient . prefetchQuery ({
queryKey: [ 'todos' ],
queryFn: fetchTodos ,
})
fetchInfiniteQuery
Fetches an infinite query and returns a promise with the infinite data structure.
fetchInfiniteQuery < TQueryFnData , TError , TData , TQueryKey , TPageParam >(
options : FetchInfiniteQueryOptions < TQueryFnData , TError , TData , TQueryKey , TPageParam >
): Promise < InfiniteData < TData , TPageParam >>
options
FetchInfiniteQueryOptions
required
Options for fetching the infinite query A unique key for the query.
The function that fetches pages.
The default page param to use when fetching the first page.
getNextPageParam
(lastPage, allPages, lastPageParam, allPageParams) => TPageParam | undefined
required
Function to get the next page param.
getPreviousPageParam
(firstPage, allPages, firstPageParam, allPageParams) => TPageParam | undefined
Function to get the previous page param.
The number of pages to fetch.
Returns a promise that resolves with the infinite query data.
prefetchInfiniteQuery
Prefetches an infinite query and caches the result.
prefetchInfiniteQuery < TQueryFnData , TError , TData , TQueryKey , TPageParam >(
options : FetchInfiniteQueryOptions < TQueryFnData , TError , TData , TQueryKey , TPageParam >
): Promise < void >
getQueryData
Returns the cached data for a query. This is a synchronous, non-reactive way to read data.
getQueryData < TQueryFnData , TTaggedQueryKey >(
queryKey : TTaggedQueryKey
): TQueryFnData | undefined
The query key to get data for.
Returns the cached data or undefined if not found.
Example
const data = queryClient . getQueryData ([ 'todos' ])
Do not use this inside components, as it won’t receive updates. Use useQuery instead.
setQueryData
Updates the cached data for a query. Can accept a value or an updater function.
setQueryData < TQueryFnData , TTaggedQueryKey >(
queryKey : TTaggedQueryKey ,
updater : Updater < TQueryFnData | undefined , TQueryFnData | undefined > ,
options ?: SetDataOptions
): TQueryFnData | undefined
The query key to update data for.
updater
TQueryFnData | ((oldData: TQueryFnData | undefined) => TQueryFnData)
required
New data value or updater function.
Additional options for setting data.
Returns the updated data.
Example
// Set with value
queryClient . setQueryData ([ 'todos' ], newTodos )
// Set with updater function
queryClient . setQueryData ([ 'todos' ], ( old ) => [ ... old , newTodo ])
getQueriesData
Returns the cached data for multiple queries matching the provided filters.
getQueriesData < TQueryFnData , TQueryFilters >(
filters : TQueryFilters
): Array < [ QueryKey , TQueryFnData | undefined ] >
Filters to match queries.
Array<[QueryKey, TQueryFnData | undefined]>
Returns an array of [queryKey, data] tuples.
setQueriesData
Updates the cached data for multiple queries matching the provided filters.
setQueriesData < TQueryFnData , TQueryFilters >(
filters : TQueryFilters ,
updater : Updater < TQueryFnData | undefined , TQueryFnData | undefined > ,
options ?: SetDataOptions
): Array < [ QueryKey , TQueryFnData | undefined ] >
getQueryState
Returns the query state (data, status, timestamps, etc.) for a query.
getQueryState < TQueryFnData , TError , TTaggedQueryKey >(
queryKey : TTaggedQueryKey
): QueryState < TQueryFnData , TError > | undefined
The query key to get state for.
Returns the query state or undefined if not found. The error if the query is in an error state.
status
'pending' | 'error' | 'success'
The status of the query.
fetchStatus
'fetching' | 'paused' | 'idle'
The fetch status of the query.
ensureQueryData
Ensures that query data is available. If data is not cached, it will fetch it.
ensureQueryData < TQueryFnData , TError , TData , TQueryKey >(
options : EnsureQueryDataOptions < TQueryFnData , TError , TData , TQueryKey >
): Promise < TData >
options
EnsureQueryDataOptions
required
Options including queryKey, queryFn, and optional revalidateIfStale.
Returns a promise that resolves with the query data (either cached or freshly fetched).
ensureInfiniteQueryData
Ensures that infinite query data is available.
ensureInfiniteQueryData < TQueryFnData , TError , TData , TQueryKey , TPageParam >(
options : EnsureInfiniteQueryDataOptions < TQueryFnData , TError , TData , TQueryKey , TPageParam >
): Promise < InfiniteData < TData , TPageParam >>
invalidateQueries
Marks queries as stale and optionally refetches them.
invalidateQueries < TTaggedQueryKey >(
filters ?: InvalidateQueryFilters < TTaggedQueryKey > ,
options ?: InvalidateOptions
): Promise < void >
Filters to match queries to invalidate. Whether to match the query key exactly.
refetchType
'active' | 'inactive' | 'all' | 'none'
Which queries to refetch. Default is ‘active’.
Additional options for invalidation.
Returns a promise that resolves when invalidation is complete.
Example
// Invalidate all queries
await queryClient . invalidateQueries ()
// Invalidate specific queries
await queryClient . invalidateQueries ({ queryKey: [ 'todos' ] })
// Invalidate without refetching
await queryClient . invalidateQueries (
{ queryKey: [ 'todos' ] },
{ refetchType: 'none' }
)
refetchQueries
Refetches queries matching the provided filters.
refetchQueries < TTaggedQueryKey >(
filters ?: RefetchQueryFilters < TTaggedQueryKey > ,
options ?: RefetchOptions
): Promise < void >
Filters to match queries to refetch. type
'active' | 'inactive' | 'all'
Which queries to refetch. Default is ‘active’.
Whether to match the query key exactly.
Only refetch stale queries.
Additional options for refetching. Whether to cancel any ongoing refetch. Default is true.
Returns a promise that resolves when refetching is complete.
Example
// Refetch all active queries
await queryClient . refetchQueries ()
// Refetch specific queries
await queryClient . refetchQueries ({ queryKey: [ 'todos' ] })
// Refetch all queries (including inactive)
await queryClient . refetchQueries ({ type: 'all' })
cancelQueries
Cancels ongoing queries matching the provided filters.
cancelQueries < TTaggedQueryKey >(
filters ?: QueryFilters < TTaggedQueryKey > ,
cancelOptions ?: CancelOptions
): Promise < void >
Filters to match queries to cancel.
Options for cancellation. Whether to revert to previous data. Default is true.
Returns a promise that resolves when cancellation is complete.
Example
await queryClient . cancelQueries ({ queryKey: [ 'todos' ] })
resetQueries
Resets queries to their initial state and optionally refetches them.
resetQueries < TTaggedQueryKey >(
filters ?: QueryFilters < TTaggedQueryKey > ,
options ?: ResetOptions
): Promise < void >
Filters to match queries to reset.
Returns a promise that resolves when reset is complete.
removeQueries
Removes queries from the cache matching the provided filters.
removeQueries < TTaggedQueryKey >(
filters ?: QueryFilters < TTaggedQueryKey >
): void
Filters to match queries to remove.
Example
queryClient . removeQueries ({ queryKey: [ 'todos' ], type: 'inactive' })
isFetching
Returns the number of queries currently fetching.
isFetching < TQueryFilters >(
filters ?: TQueryFilters
): number
Filters to match queries.
The number of queries currently fetching.
Example
const isFetching = queryClient . isFetching ()
const isFetchingTodos = queryClient . isFetching ({ queryKey: [ 'todos' ] })
isMutating
Returns the number of mutations currently executing.
isMutating < TMutationFilters >(
filters ?: TMutationFilters
): number
Filters to match mutations.
The number of mutations currently executing.
getQueryCache
Returns the QueryCache instance used by this client.
getQueryCache (): QueryCache
getMutationCache
Returns the MutationCache instance used by this client.
getMutationCache (): MutationCache
The MutationCache instance.
getDefaultOptions
Returns the default options for this client.
getDefaultOptions (): DefaultOptions
setDefaultOptions
Sets the default options for this client.
setDefaultOptions ( options : DefaultOptions ): void
setQueryDefaults
Sets default options for queries matching a specific query key.
setQueryDefaults < TQueryFnData , TError , TData , TQueryData >(
queryKey : QueryKey ,
options : Partial < QueryObserverOptions < TQueryFnData , TError , TData , TQueryData >>
): void
The query key to set defaults for.
options
Partial<QueryObserverOptions>
required
The default options for this query key.
Example
queryClient . setQueryDefaults ([ 'todos' ], {
staleTime: 1000 * 60 * 5 ,
})
getQueryDefaults
Gets the default options for queries matching a specific query key.
getQueryDefaults ( queryKey : QueryKey ): Partial < QueryObserverOptions >
The query key to get defaults for.
Partial<QueryObserverOptions>
The default options for this query key.
setMutationDefaults
Sets default options for mutations matching a specific mutation key.
setMutationDefaults < TData , TError , TVariables , TOnMutateResult >(
mutationKey : MutationKey ,
options : Partial < MutationObserverOptions < TData , TError , TVariables , TOnMutateResult >>
): void
The mutation key to set defaults for.
options
Partial<MutationObserverOptions>
required
The default options for this mutation key.
getMutationDefaults
Gets the default options for mutations matching a specific mutation key.
getMutationDefaults ( mutationKey : MutationKey ): Partial < MutationObserverOptions >
mount
Mounts the QueryClient, setting up focus and online event listeners.
unmount
Unmounts the QueryClient, removing focus and online event listeners.
clear
Clears all caches (queries and mutations).
Example
resumePausedMutations
Resumes all paused mutations.
resumePausedMutations (): Promise < unknown >
Returns a promise that resolves when all paused mutations have resumed.