The QueryCache is responsible for storing and managing all Query instances. It’s the underlying storage mechanism used by QueryClient.
Constructor
Creates a new QueryCache instance.
const queryCache = new QueryCache ( config ?: QueryCacheConfig )
Configuration options for the QueryCache onError
(error: Error, query: Query) => void
Global error handler called when any query encounters an error.
onSuccess
(data: unknown, query: Query) => void
Global success handler called when any query succeeds.
onSettled
(data: unknown | undefined, error: Error | null, query: Query) => void
Global settled handler called when any query completes (success or error).
Example
import { QueryCache } from '@tanstack/query-core'
const queryCache = new QueryCache ({
onError : ( error , query ) => {
console . log ( `Query ${ query . queryHash } failed:` , error )
},
onSuccess : ( data , query ) => {
console . log ( `Query ${ query . queryHash } succeeded` )
},
})
Methods
build
Builds or retrieves a query instance. If a query with the same hash exists, it returns that query. Otherwise, it creates a new one.
build < TQueryFnData , TError , TData , TQueryKey >(
client : QueryClient ,
options : QueryOptions < TQueryFnData , TError , TData , TQueryKey > ,
state ?: QueryState < TData , TError >
): Query < TQueryFnData , TError , TData , TQueryKey >
The QueryClient instance.
Options for the query including queryKey and queryHash.
Optional initial state for a new query.
Returns the Query instance (either existing or newly created).
add
Adds a query to the cache.
The query instance to add.
remove
Removes a query from the cache and destroys it.
remove ( query : Query ): void
The query instance to remove.
clear
Clears all queries from the cache.
Example
get
Retrieves a query from the cache by its query hash.
get < TQueryFnData , TError , TData , TQueryKey >(
queryHash : string
): Query < TQueryFnData , TError , TData , TQueryKey > | undefined
The hash of the query to retrieve.
Returns the Query instance if found, otherwise undefined.
getAll
Returns all queries in the cache.
Returns an array of all Query instances in the cache.
Example
const allQueries = queryCache . getAll ()
console . log ( `Total queries: ${ allQueries . length } ` )
find
Finds a single query matching the provided filters.
find < TQueryFnData , TError , TData >(
filters : QueryFilters
): Query < TQueryFnData , TError , TData > | undefined
Filters to match queries. Whether to match the query key exactly. Default is true.
Returns the first matching Query instance, or undefined if not found.
Example
const todoQuery = queryCache . find ({ queryKey: [ 'todos' ], exact: true })
findAll
Finds all queries matching the provided filters.
findAll ( filters ?: QueryFilters ): Array < Query >
Filters to match queries. If not provided, returns all queries. Whether to match the query key exactly.
type
'active' | 'inactive' | 'all'
Filter by query type.
fetchStatus
'fetching' | 'paused' | 'idle'
Filter by fetch status.
predicate
(query: Query) => boolean
Custom predicate function.
Returns an array of all matching Query instances.
Example
// Find all active queries
const activeQueries = queryCache . findAll ({ type: 'active' })
// Find all stale queries with a specific key
const staleTodos = queryCache . findAll ({
queryKey: [ 'todos' ],
stale: true
})
// Find queries with custom predicate
const queries = queryCache . findAll ({
predicate : ( query ) => query . state . data !== undefined
})
notify
Notifies all cache listeners of an event.
notify ( event : QueryCacheNotifyEvent ): void
event
QueryCacheNotifyEvent
required
The event to notify listeners about.
subscribe
Subscribes to cache events.
subscribe ( listener : QueryCacheListener ): () => void
listener
(event: QueryCacheNotifyEvent) => void
required
Function called when cache events occur.
Returns an unsubscribe function.
Example
const unsubscribe = queryCache . subscribe (( event ) => {
console . log ( 'Cache event:' , event . type )
if ( event . type === 'added' ) {
console . log ( 'Query added:' , event . query . queryHash )
} else if ( event . type === 'updated' ) {
console . log ( 'Query updated:' , event . query . queryHash )
} else if ( event . type === 'removed' ) {
console . log ( 'Query removed:' , event . query . queryHash )
}
})
// Later, unsubscribe
unsubscribe ()
Events
The QueryCache emits the following events:
added
Fired when a query is added to the cache.
{
type : 'added'
query : Query
}
removed
Fired when a query is removed from the cache.
{
type : 'removed'
query : Query
}
updated
Fired when a query is updated.
{
type : 'updated'
query : Query
action : Action
}
observerAdded
Fired when an observer is added to a query.
{
type : 'observerAdded'
query : Query
observer : QueryObserver
}
observerRemoved
Fired when an observer is removed from a query.
{
type : 'observerRemoved'
query : Query
observer : QueryObserver
}
observerResultsUpdated
Fired when observer results are updated.
{
type : 'observerResultsUpdated'
query : Query
}
observerOptionsUpdated
Fired when observer options are updated.
{
type : 'observerOptionsUpdated'
query : Query
observer : QueryObserver
}
Internal Methods
onFocus
Called when the window regains focus. Triggers onFocus on all queries.
onOnline
Called when the network comes back online. Triggers onOnline on all queries.
Usage with QueryClient
While you can use QueryCache directly, it’s typically used through a QueryClient:
import { QueryClient , QueryCache } from '@tanstack/query-core'
// Custom cache with event handlers
const queryCache = new QueryCache ({
onError : ( error ) => {
console . error ( 'Global query error:' , error )
},
})
// Use custom cache with QueryClient
const queryClient = new QueryClient ({
queryCache ,
})