QueryCache

· abundance's blog


The QueryCache is the storage mechanism for TanStack Query. It stores all the data, meta information and state of queries it contains.

Normally, you will not interact with the QueryCache directly and instead use the QueryClient for a specific cache.

 1import { QueryCache } from '@tanstack/react-query'
 2
 3const queryCache = new QueryCache({
 4  onError: (error) => {
 5    console.log(error)
 6  },
 7  onSuccess: (data) => {
 8    console.log(data)
 9  },
10  onSettled: (data, error) => {
11    console.log(data, error)
12  },
13})
14
15const query = queryCache.find(['posts'])

Its available methods are:

Options

queryCache.find #

find is a slightly more advanced synchronous method that can be used to get an existing query instance from the cache. This instance not only contains all the state for the query, but all of the instances, and underlying guts of the query as well. If the query does not exist, undefined will be returned.

Note: This is not typically needed for most applications, but can come in handy when needing more information about a query in rare scenarios (eg. Looking at the query.state.dataUpdatedAt timestamp to decide whether a query is fresh enough to be used as an initial value)

1const query = queryCache.find(queryKey)

Options

Returns

queryCache.findAll #

findAll is even more advanced synchronous method that can be used to get existing query instances from the cache that partially match query key. If queries do not exist, empty array will be returned.

Note: This is not typically needed for most applications, but can come in handy when needing more information about a query in rare scenarios

1const queries = queryCache.findAll(queryKey)

Options

Returns

queryCache.subscribe #

The subscribe method can be used to subscribe to the query cache as a whole and be informed of safe/known updates to the cache like query states changing or queries being updated, added or removed

1const callback = (event) => {
2  console.log(event.type, event.query)
3}
4
5const unsubscribe = queryCache.subscribe(callback)

Options

Returns

queryCache.clear #

The clear method can be used to clear the cache entirely and start fresh.

1queryCache.clear()

Further reading #

To get a better understanding how the QueryCache works internally, have a look at #18: Inside React Query from the Community Resources.