Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 38 ยท Testing and DevTools

Debugging and Production Monitoring

A field guide to TanStack Query problems: stale data, extra refetches, unstable keys, re-render storms, and how to log and monitor queries and mutations in production.

Most TanStack Query bugs fall into a handful of families. Once you know the family, the fix is usually one line. This lesson is a field guide: symptoms, causes, and the tools (devtools, cache subscriptions, small experiments) to confirm them. At the end you will wire logging that works in production, where there is no devtools panel.

Symptom 1: data does not update after a mutation

Cause: the invalidated key does not match the query's key.

Invalidation matches by prefix and by structural equality of the key parts:

JavaScript
queryClient.invalidateQueries({ queryKey: ["todos"] });            // matches ["todos"], ["todos", 3], ["todos", { page: 2 }]
queryClient.invalidateQueries({ queryKey: ["todo"] });             // matches nothing: a typo
queryClient.invalidateQueries({ queryKey: ["todos"], exact: true }); // only ["todos"] exactly

Object parts are compared by value, and key order inside objects does not matter ({ a: 1, b: 2 } equals { b: 2, a: 1 }), but array order does (["a", "b"] is not ["b", "a"]). Keep keys in a small factory so typos are impossible:

JavaScript
export const todoKeys = {
  all: ["todos"],
  list: (filters) => [...todoKeys.all, "list", filters],
  detail: (id) => [...todoKeys.all, "detail", id],
};
JS Which queries does invalidation match?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

findAll uses the same matching as invalidateQueries, refetchQueries, removeQueries and cancelQueries. When you doubt a filter, print what it matches.

Symptom 2: too many requests

Check these in order:

  1. staleTime is 0. By default every mount, window focus and reconnect refetches. Set a staleTime that fits the data (for example 30_000 for lists, Infinity for reference data), globally in defaultOptions and override per query.
  2. The key changes every render. queryKey: ["items", new Date()] or an inline object with a function inside makes a new key each time. Keys must be stable and JSON-serializable.
  3. Many components mount the same query. That is fine: they share one request (deduplication), provided the keys match.
  4. refetchOnWindowFocus. Great for dashboards, annoying during development with devtools open. Disable it per query or globally when the data cannot go stale.
  5. refetchInterval too short, or invalidateQueries inside a render path.

Symptom 3: the UI shows stale or wrong data

  • Cached data for a different filter: the filter is missing from the key.
  • initialData without staleTime: it refetches at once, and a "flash" of the old value shows first.
  • Closure bugs in the queryFn: the function reads a variable that is not in the key. Treat the key like the dependency array of an effect: every value used in queryFn belongs in it.
  • Persisted cache from an older app version: use a buster or clear the persisted storage after deploys.

Symptom 4: too many re-renders

A component using useQuery re-renders on many internal changes: isFetching toggles, dataUpdatedAt, failureCount. TanStack Query tracks which fields you actually read and re-renders only for those (tracked properties), but it works only if you read fields lazily:

JSX
const query = useQuery(opts);          // good: reads query.data only
return <List items={query.data} />;

const { data, ...rest } = useQuery(opts); // bad: spreading rest reads every field and disables tracking

Other cures:

  • select transforms or narrows the data. The component re-renders only when the selected result changes (compared structurally). Memoize heavy selectors with a stable function reference.
  • Split components so only the one that needs isFetching reads it.
  • notifyOnChangeProps: ["data"] is available, but tracked properties (the default) usually does this automatically.
JS select limits re-renders

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The observer without select is notified for both updates; the one selecting count is notified only when the count actually changes.

Symptom 5: flickering loading states

Using isLoading (pending and fetching) versus isPending (no data yet) versus isFetching (any request) causes most confusion:

Flag True when Use for
isPending there is no data yet first-load skeleton
isFetching any request is running a small "refreshing" indicator
isLoading pending and fetching first load of an enabled query
isRefetching fetching while data exists "updating..." badges
isPlaceholderData showing placeholder dimming old data

For a disabled query (enabled: false) isPending is true forever (no data yet) while isLoading is false (nothing is fetching), so use isLoading for spinners of conditional queries.

Production monitoring

Devtools are a development tool. In production, use the cache events and global callbacks to feed your monitoring service (Sentry, Datadog, your own endpoint):

JavaScript
const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error, query) => {
      report("query_error", { key: query.queryKey, message: error.message });
    },
  }),
  mutationCache: new MutationCache({
    onError: (error, variables, context, mutation) => {
      report("mutation_error", { key: mutation.options.mutationKey, message: error.message });
    },
  }),
});

Useful signals to track:

  • Error rate per query key prefix (are ["checkout", ...] queries failing?).
  • Slow queries: measure the time between fetching and success events.
  • Retry counts: query.state.fetchFailureCount.
  • Cache size: queryClient.getQueryCache().getAll().length on a timer, to catch key explosions.
JS Measure query durations from cache events

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Send those numbers to your monitoring tool and you will see regressions long before users complain. Never include query data or user input in reports; keys and messages are normally enough, and keys should not contain secrets.

A debugging routine

  1. Reproduce with the devtools open. Find the query row. Is it the key you expect?
  2. Read its state (fresh/stale/fetching) and observer count.
  3. Compare key against invalidation and prefetch calls.
  4. Print queryCache.findAll(filters) for any filter you doubt.
  5. Check what the queryFn closes over: is every value in the key?
  6. Reduce: reproduce with a tiny fake API in a sandbox like the editors in this lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. invalidateQueries({ queryKey: ['todos'] }) matches which keys?

    Matching is by prefix unless exact: true is passed.
  2. 2. Which pattern disables tracked-property optimization and causes extra re-renders?

    Spreading the rest of the result reads every field, so the component re-renders for every internal change.
  3. 3. A disabled query (enabled: false) with no data: which flag is true?

    isPending means no data yet. isLoading is false because nothing is fetching.
  4. 4. Where do you hook global error reporting in v5?

    Cache-level callbacks run once for every query or mutation, which is the right place for monitoring.

Summary

  • Update bugs are almost always key mismatches; use key factories and findAll to check matches.
  • Extra requests come from staleTime: 0, unstable keys or aggressive refetch triggers.
  • Reduce re-renders by reading fields lazily, using select and splitting components.
  • Know isPending, isLoading, isFetching and isRefetching.
  • Report errors and slow queries with cache and mutation callbacks and queryCache.subscribe.

Next: Project: Issue Tracker