Skip to main content

Overview

The QueryCache is responsible for storing and managing all Query instances. It provides methods to build, access, and manipulate queries, and emits events when queries are added, removed, or updated.

Constructor

const queryCache = new QueryCache(config?: QueryCacheConfig)
config
QueryCacheConfig
Configuration options for the QueryCache
Example:
const queryCache = new QueryCache({
  onError: (error, query) => {
    console.error('Query error:', error, 'Query key:', query.queryKey)
  },
  onSuccess: (data, query) => {
    console.log('Query success:', query.queryKey)
  },
})

Methods

build()

Builds or retrieves a query instance.
const query = queryCache.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
Query options including queryKey
state
QueryState
Initial state for the query
Returns: A Query instance
If a query with the same hash already exists, it returns the existing query. Otherwise, creates a new one.

add()

Adds a query to the cache.
queryCache.add(query: Query): void
query
Query
required
The query instance to add
This method is typically called internally by the build() method.

remove()

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

clear()

Removes all queries from the cache.
queryCache.clear(): void
Example:
queryCache.clear()

get()

Retrieves a query from the cache by its hash.
const query = queryCache.get<TQueryFnData, TError, TData, TQueryKey>(
  queryHash: string
): Query<TQueryFnData, TError, TData, TQueryKey> | undefined
queryHash
string
required
The hash of the query to retrieve
Returns: The Query instance or undefined if not found Example:
const query = queryCache.get('["\'todos\'"]')

getAll()

Returns all queries in the cache.
const queries = queryCache.getAll(): Array<Query>
Returns: Array of all Query instances Example:
const allQueries = queryCache.getAll()
console.log(`Total queries: ${allQueries.length}`)

find()

Finds a single query that matches the filters.
const query = queryCache.find<TQueryFnData, TError, TData>(
  filters: QueryFilters
): Query<TQueryFnData, TError, TData> | undefined
filters
QueryFilters
required
Filters to match queries
Returns: The first matching Query or undefined Example:
const todoQuery = queryCache.find({ queryKey: ['todos', 1], exact: true })

findAll()

Finds all queries that match the filters.
const queries = queryCache.findAll(filters?: QueryFilters): Array<Query>
filters
QueryFilters
Filters to match queries
Returns: Array of matching Query instances Example:
// Find all queries with 'todos' in the key
const todoQueries = queryCache.findAll({ queryKey: ['todos'] })

// Find all stale queries
const staleQueries = queryCache.findAll({ stale: true })

// Find all fetching queries
const fetchingQueries = queryCache.findAll({ fetchStatus: 'fetching' })

notify()

Notifies all subscribers of a cache event.
queryCache.notify(event: QueryCacheNotifyEvent): void
event
QueryCacheNotifyEvent
required
The event to notify subscribers about

subscribe()

Subscribes to cache events.
const unsubscribe = queryCache.subscribe(
  listener: (event: QueryCacheNotifyEvent) => void
): () => void
listener
(event: QueryCacheNotifyEvent) => void
required
Callback function to handle cache events
Returns: Function to unsubscribe Example:
const unsubscribe = queryCache.subscribe((event) => {
  if (event.type === 'added') {
    console.log('Query added:', event.query.queryKey)
  }
  if (event.type === 'updated') {
    console.log('Query updated:', event.query.queryKey)
  }
})

// Later, unsubscribe
unsubscribe()

onFocus()

Called when the window regains focus. Triggers focus events on all queries.
queryCache.onFocus(): void
This method is typically called automatically by the QueryClient.

onOnline()

Called when the network comes back online. Triggers online events on all queries.
queryCache.onOnline(): void
This method is typically called automatically by the QueryClient.

Events

The QueryCache emits the following events:
  • added - When a query is added to the cache
  • removed - When a query is removed from the cache
  • updated - When a query’s state changes
  • observerAdded - When an observer subscribes to a query
  • observerRemoved - When an observer unsubscribes from a query
  • observerResultsUpdated - When observer results are updated
  • observerOptionsUpdated - When observer options are updated

Usage with QueryClient

const queryCache = new QueryCache()

const queryClient = new QueryClient({
  queryCache,
})

Build docs developers (and LLMs) love