Sub topic 15
Inspecting the cache with the Devtools
This chapter assumes you have read the chapters on staleTime, gcTime, query keys, and invalidation. You should be able to render a component with useQuery and explain what a query key is. The Devtools show those ideas as live data, so you can check your mental model against the real cache.
What the Devtools show
The React Query Devtools are a floating panel that reads the QueryClient cache and displays every query and mutation in it. They help with three common problems:
- A query refetches more often than you expected.
- A query never refetches when you expected it to.
- A query key does not match the one you invalidate.
The panel does not change how your app works. It observes the cache, and it offers a few buttons that act on it.
Installing and mounting
The Devtools ship as a separate package.
npm install @tanstack/react-query-devtoolsMount ReactQueryDevtools inside QueryClientProvider. It reads the client from context, so it must be a descendant of the provider.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
const queryClient = new QueryClient()
export function App() {
return (
<QueryClientProvider client={queryClient}>
<Todos />
<ReactQueryDevtools initialIsOpen={false} buttonPosition="bottom-right" />
</QueryClientProvider>
)
}initialIsOpen={false} keeps the panel closed until you click the floating button. buttonPosition moves that button. The panel itself has a separate position prop ("top", "bottom", "left", or "right").
If you can't render it inside the provider, pass the client explicitly with the client prop.
<ReactQueryDevtools client={queryClient} />Devtools and production builds
By default, ReactQueryDevtools renders nothing when process.env.NODE_ENV === 'production'. Your bundler normally removes it from production bundles, so you don't need to add a condition yourself.
If you want the Devtools in a deployed environment, such as a staging site, import the production build and load it lazily. The first line below is the import path. The rest sets up a lazy wrapper.
import React from 'react'
const ReactQueryDevtoolsProduction = React.lazy(() =>
import('@tanstack/react-query-devtools/production').then((d) => ({
default: d.ReactQueryDevtools,
})),
)Render it inside a <React.Suspense fallback={null}> boundary, and show it only when a flag you control is set. Think about who can reach that flag. The panel exposes your cached data, including anything private the current user has fetched.
Reading the query list
Each row in the list is one cache entry. The row shows the serialized query key and a small number on the left. That number is the count of observers, the mounted components currently subscribed through useQuery. The row color shows the query's state.
| State | Meaning | What caused it |
|---|---|---|
| fresh | Data is younger than `staleTime` | A recent fetch with `staleTime` above 0 |
| fetching | A request is in flight | Mount, refetch, window focus, invalidation |
| paused | A fetch wants to run but the network is offline | `networkMode: 'online'` with no connection |
| stale | Data is older than `staleTime` | The default `staleTime` is 0, so data is stale right away |
| inactive | No observers are mounted | All components using the key unmounted |
The panel also shows how many queries are in each state in its header. A query can be fetching and stale at once. The Devtools show the most informative label for each case.
Most of the rows you see will be stale. That is the default, not a bug. With staleTime: 0, data is stale the moment it arrives, which is why a remount or a window focus triggers a background refetch.
The states change over time as events happen. This diagram shows the common path of one query.
Reading the query details
Click a row to open its details. The fields to check first:
- Query key. The exact array stored in the cache. Compare it against the key you pass to
invalidateQueries. - Observers. How many components currently use the query.
- Last updated. When the data last arrived. This tells you whether
staleTimeis behaving as intended. - Data explorer. The cached value, which you can expand.
- Query explorer. The full internal query object, including its state.
The details panel also has action buttons.
| Action | Effect | Use it to |
|---|---|---|
| Refetch | Fetches again now | Confirm the `queryFn` still works |
| Invalidate | Marks stale and refetches if observed | Test your invalidation keys |
| Reset | Returns the query to its initial state | Replay the first load |
| Remove | Deletes the entry from the cache | Check behavior with a cold cache |
| Trigger loading | Forces a loading state | Style your pending UI |
| Trigger error | Forces an error state | Style your error UI |
The last two actions are useful because they let you see the pending and error branches of a component without editing the queryFn. A forced state is not a real fetch, so treat it as a visual check only.
A worked check: does my key match?
A common bug is invalidating a key that does not match the one the query uses. Consider this setup.
import { useQuery, useQueryClient } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
async function fetchTodos(filter: string): Promise<Todo[]> {
const res = await fetch(`/api/todos?filter=${filter}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function FilteredTodos({ filter }: { filter: string }) {
const queryClient = useQueryClient()
const { data } = useQuery({
queryKey: ['todos', 'list', { filter }],
queryFn: () => fetchTodos(filter),
staleTime: 30 * 1000,
})
return (
<div>
<button
onClick={() => queryClient.invalidateQueries({ queryKey: ['todo'] })}
>
Refresh
</button>
<p>{data?.length ?? 0} todos</p>
</div>
)
}The button does nothing visible. Open the Devtools and you will see a row for ["todos","list",{"filter":"all"}]. Click the button, and the row does not flash blue, so no refetch ran. The invalidation key is ['todo'], which is a typo. It does not match the prefix ['todos'].
Change the key to ['todos']. Click the button again. The row turns blue while fetching, then green because staleTime is 30 seconds. The Last updated field resets. Because invalidation matches by prefix, ['todos'] reaches every key that starts with todos, including the list for each filter.
Observing garbage collection
You can watch gcTime work. Set a short value and navigate away.
const { data } = useQuery({
queryKey: ['todos', 'list', { filter }],
queryFn: () => fetchTodos(filter),
gcTime: 10 * 1000,
})Unmount the component, for example by switching routes. The row turns gray (inactive), and after about 10 seconds it disappears. Return to the screen and the query starts in a pending state because nothing was cached. With the default gcTime of five minutes, the entry would still be there and the data would show immediately while a background refetch ran.
Common pitfalls
- Strict Mode doubles mounts in development. React Strict Mode mounts components twice, so you may see an extra observer or an extra fetch. Check a production build before you chase it.
- Several
QueryClientinstances. If you create a client inside a component without memoizing it, each render creates an empty cache. The Devtools will show a cache that keeps resetting. Create the client once, outside the component or inuseState. - Wrong client. If your app has more than one provider, the Devtools show the nearest one, or the one you pass through
client. - Stale rows are normal. Do not set a large
staleTimeonly to turn rows green. Set it because the data really can be reused.
Exercise
A query uses queryKey: ['projects', { page: 2 }]. In the Devtools you click Invalidate and the row refetches, but your code calling queryClient.invalidateQueries({ queryKey: ['project'] }) does nothing. What is wrong, and what is the fix?
Show answer
The key ['project'] is not a prefix of ['projects', { page: 2 }], because the first element is 'project' and not 'projects'. Invalidation matches keys by prefix, so nothing matches. The Invalidate button works because it targets that exact entry. Change the call to invalidateQueries({ queryKey: ['projects'] }).
Exercise
You set gcTime: 10_000 on a query, then unmount the only component that uses it. What do you see in the Devtools, and what happens when you remount the component 30 seconds later?
Show answer
The row turns gray (inactive) right after the unmount. About 10 seconds later the entry is removed from the cache. On remount 30 seconds later there is no cached data, so the query starts in a pending state and fetches from scratch.