Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Caching and Staleness

Working with the Cache Directly

A tour of the QueryClient cache methods: fetchQuery, ensureQueryData, refetchQueries, cancelQueries, removeQueries, resetQueries, clear, and subscribing to cache events.

Hooks cover most of what you do. For everything else, loaders, event handlers, tests, logout flows, there is the QueryClient itself. This lesson is a guided tour of its cache methods so you can pick the right one: reading, fetching on demand, refetching, cancelling, removing, resetting, and watching what the cache does. You have already met setQueryData, getQueryData and invalidateQueries; here they are placed among their relatives.

Reading and writing

Method What it does
getQueryData(key) Returns cached data or undefined; no fetch
getQueryState(key) Returns the full state (status, timestamps, error)
setQueryData(key, data or updater) Writes data, no fetch
setQueriesData(filters, updater) Writes to every matching existing query
getQueriesData(filters) Returns [key, data] pairs for every match

These are synchronous and never touch the network. Details are in Updating the Cache from Responses.

Fetching imperatively

Sometimes you need data outside a component: a route loader, a click handler that must wait for data, a prefetch on hover.

Method Behavior
fetchQuery(options) Fetches if there is no fresh data; returns a promise of the data; throws on error
prefetchQuery(options) Same, but returns nothing and never throws; it warms the cache
ensureQueryData(options) Returns cached data if any (even stale); otherwise fetches
fetchInfiniteQuery, prefetchInfiniteQuery, ensureInfiniteQueryData The same for infinite queries

The difference between fetchQuery and ensureQueryData matters. fetchQuery respects staleTime: data older than that is refetched. ensureQueryData returns whatever exists, however old, and only fetches when the cache is empty, which is ideal in a router loader that should not block on a background refresh.

fetchQuery, ensureQueryData and prefetchQuery

Prefetching has its own lesson, Prefetching and Initial Data, which uses these methods to make navigation feel instant.

Refetching and cancelling

Method Behavior
refetchQueries(filters) Refetches matching queries now, even if fresh (active ones by default)
invalidateQueries(filters) Marks stale, then refetches the active ones
cancelQueries(filters) Cancels in-flight requests and reverts their state
isFetching(filters) Number of queries currently fetching
isMutating(filters) Number of mutations currently pending

cancelQueries is the method you call at the start of an optimistic update, so a slow response from before the change cannot overwrite what you just wrote. For cancellation to abort the actual HTTP request, the queryFn must use the signal, as explained in Query Functions; otherwise the request finishes but its result is ignored.

Removing and resetting

Three methods end the life of data, and they are easy to confuse:

Method Cache entry Observers on screen
removeQueries(filters) Deleted Not refetched; mounted components keep their last data until something triggers a fetch
resetQueries(filters) Reset to its initial state, then active ones refetch Show a loading state again
clear() The whole cache is emptied Everything starts from scratch

Use resetQueries when you want the UI to behave as if the data had never been loaded, for example after changing a global setting such as the language. Use removeQueries to free memory for data no one is looking at. Use queryClient.clear() on logout: leftover cached data from the previous user must never appear for the next one.

JavaScript
async function logout() {
  await api.logout();
  queryClient.clear();         // drop every cached query and mutation
  navigate("/login");
}

On shared computers, skipping clear() after logout is a privacy bug. Cached data of user A can flash on screen for user B until it refetches. Clear the cache (or use a client per session) at every identity change.

Watching the cache

The QueryCache is an event source. You can subscribe to everything that happens in it, which is how DevTools and logging tools work:

Subscribing to cache events

You will see events such as added, observerAdded, updated and removed, each with the query that caused them. A few uses: send metrics ("how often do we refetch?"), log failures in development, or keep another store (such as local storage persistence) in sync.

For lookups without subscribing, the cache object has find, findAll and getAll:

JavaScript
const cache = queryClient.getQueryCache();
cache.findAll({ queryKey: ["todos"] }).map((q) => q.queryKey);   // all matching queries
cache.find({ queryKey: ["todos", "detail", 5], exact: true });   // one query object or undefined

Filters: one vocabulary

Almost every method above accepts the same query filters: queryKey (prefix), exact, type ("active", "inactive", "all"), stale, fetchStatus, and predicate. Learn them once and you can target exactly the group you mean, for example "all inactive queries older than ten minutes":

JavaScript
queryClient.removeQueries({
  type: "inactive",
  predicate: (q) => Date.now() - q.state.dataUpdatedAt > 10 * 60 * 1000,
});

That wraps up this chapter on caching. You now know how data is identified (Query Keys), when it is trusted, when it refetches, how failures are absorbed, and how to act on the cache from code. The track page, TanStack Query, continues with pagination, optimistic updates, Suspense and testing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method returns cached data even if it is stale, and fetches only when the cache is empty?

    ensureQueryData is cache-first. fetchQuery refetches data older than staleTime.
  2. 2. Which method should you call at logout to avoid showing the old user's data?

    clear() empties the whole cache (queries and mutations).
  3. 3. What is the difference between prefetchQuery and fetchQuery?

    prefetchQuery warms the cache silently, while fetchQuery gives you the data or an exception.
  4. 4. Why call cancelQueries at the start of an optimistic update?

    A response that was already on its way would otherwise land after your cache write and undo it.

Summary

  • Read with getQueryData/getQueryState; write with setQueryData/setQueriesData.
  • Fetch on demand with fetchQuery (throws), prefetchQuery (silent) and ensureQueryData (cache first).
  • refetchQueries ignores freshness; invalidateQueries marks stale; cancelQueries stops requests.
  • removeQueries deletes, resetQueries returns to the initial state, clear() empties everything (use it at logout).
  • Subscribe to the QueryCache for events, and use the shared filter vocabulary to target groups of queries.

Next: Paginated Queries