Skip to main content
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)
config
QueryCacheConfig
Configuration options for the QueryCache

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>
client
QueryClient
required
The QueryClient instance.
options
QueryOptions
required
Options for the query including queryKey and queryHash.
state
QueryState
Optional initial state for a new query.
Query
Query
Returns the Query instance (either existing or newly created).

add

Adds a query to the cache.
add(query: Query): void
query
Query
required
The query instance to add.

remove

Removes a query from the cache and destroys it.
remove(query: Query): void
query
Query
required
The query instance to remove.

clear

Clears all queries from the cache.
clear(): void

Example

queryCache.clear()

get

Retrieves a query from the cache by its query hash.
get<TQueryFnData, TError, TData, TQueryKey>(
  queryHash: string
): Query<TQueryFnData, TError, TData, TQueryKey> | undefined
queryHash
string
required
The hash of the query to retrieve.
Query | undefined
Query
Returns the Query instance if found, otherwise undefined.

getAll

Returns all queries in the cache.
getAll(): Array<Query>
Array<Query>
Array
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
QueryFilters
required
Filters to match queries.
Query | undefined
Query
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
QueryFilters
Filters to match queries. If not provided, returns all queries.
Array<Query>
Array
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.
() => void
function
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.
onFocus(): void

onOnline

Called when the network comes back online. Triggers onOnline on all queries.
onOnline(): void

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,
})

Build docs developers (and LLMs) love