invalidateQueries vs refetch in TanStack Query

IntermediateState management interview questionBy , updated 3 December 2026

Short answer

queryClient.invalidateQueries marks every query that matches a key as stale, overriding staleTime, and refetches only the active ones, the ones a mounted component is using. Inactive matches refetch the next time a component uses them. refetch, from useQuery, and queryClient.refetchQueries fetch right now, stale or not. After a mutation, invalidate. Use refetch for an explicit reload button or a query you keep disabled.

The four tools side by side

People reach for all of these after a write, so it helps to see them together:

Fetches now? Which queries Respects enabled: false? Typical use
invalidateQueries Active ones only (by default) Every match of a key prefix Yes, skips disabled queries After a mutation
refetchQueries Yes, stale or fresh Every match, inactive too unless filtered Yes, skips disabled queries Force a refresh of a group
refetch() from useQuery Yes This one query No, it works on disabled queries Reload button, manual fetch
setQueryData No request at all One exact key Not relevant Write the server's response into the cache

The short version: invalidation says "this data is out of date, refresh it where it matters". Refetch says "fetch this now".

invalidateQueries after a mutation

The docs describe three effects of invalidating a query: it is marked stale, that stale state overrides any staleTime, and if a component is rendering it, it is refetched in the background.

const queryClient = useQueryClient();

const addTodo = useMutation({
  mutationFn: createTodo,
  onSuccess: async () => {
    await queryClient.invalidateQueries({ queryKey: ["todos"] });
  },
});

Two details in that snippet are worth saying out loud in an interview:

  • Prefix matching. ["todos"] also matches ["todos", { page: 1 }] and ["todos", { status: "done" }]. One call refreshes every list view. Pass exact: true to match only ["todos"], or a predicate function for anything more specific.
  • The await. invalidateQueries returns a promise that resolves when the refetch settles. Returning or awaiting it from onSuccess keeps the mutation's isPending true until the fresh list has arrived, so the button does not re-enable while the old list is still on screen.

Inactive matches, such as a todo list on another route, are only marked stale. They do not fire requests now. When the user navigates back, the stale data shows instantly and a refetch runs on mount. That is why invalidation is cheap even with broad keys.

You can change this with refetchType: the default is "active"; "none" only marks queries stale; and "inactive" or "all" widen which matches refetch now.

refetch: fetch this one now

refetch comes from the useQuery result and always runs the query function, whatever staleTime says.

const { data, refetch, isFetching } = useQuery({
  queryKey: ["report", reportId],
  queryFn: () => fetchReport(reportId),
  enabled: false, // only fetch when the user asks
});

return (
  <button onClick={() => refetch()} disabled={isFetching}>
    Generate report
  </button>
);

This is the one case where refetch is clearly right: a disabled query ignores invalidateQueries and refetchQueries from the client, but the refetch returned by useQuery still triggers it. Note that this does not work with skipToken; calling refetch on a query that uses it fails with a "Missing queryFn" error, so use enabled: false when you need manual fetches.

By default a new refetch cancels a fetch that is already running for that query (cancelRefetch: true). Pass { cancelRefetch: false } to keep the running one instead.

refetchQueries: the client-wide hammer

queryClient.refetchQueries({ queryKey: ["todos"] }) refetches every matching query "regardless of whether they are stale". The query filter's type defaults to "all", so inactive queries are included. That can mean requests for screens nobody is looking at. Add type: "active" if you really want a forced refresh of what is visible. In most code, invalidateQueries is the better default: it refreshes what is on screen and lazily refreshes the rest.

Where setQueryData fits

If the mutation's response already contains the new object, you can skip the request entirely:

onSuccess: (updatedTodo) => {
  queryClient.setQueryData(["todo", updatedTodo.id], updatedTodo);
},

setQueryData writes synchronously and must be immutable: return a new object, never change oldData in place. It updates one exact key, so it suits a detail view. Lists that might change order, totals or pagination are usually safer to invalidate. Many apps do both: set the detail, invalidate the lists. The optimistic version of this pattern is in optimistic updates with TanStack Query.

To build the matching and invalidation yourself, try Build a mini React Query, then TanStack Query's key helpers for partialMatchKey, and a useMutation with invalidation.

Common follow-up questions

Why not call refetch() after every mutation?

You only have refetch for the query in your own component. The same data may appear in a sidebar, a count badge and a list on another route, each under a related key. Invalidating the key prefix reaches all of them, refetches only the visible ones, and marks the rest stale for later.

Does invalidateQueries ignore staleTime?

Yes. Invalidation overrides staleTime, so even data with staleTime: Infinity is marked stale and refetched if active. That is why long stale times are safe when every write invalidates. See staleTime vs gcTime.

What is the difference between invalidateQueries and resetQueries?

resetQueries puts matching queries back to their initial state, such as initialData, and refetches active ones. The user sees a loading state again. invalidateQueries keeps the old data on screen while the refetch runs.

And removeQueries?

removeQueries deletes matching entries from the cache. Nothing refetches until a component asks for the key again. It is useful on logout, together with clearing user-specific data.

Should I await invalidateQueries?

Await it, or return it from onSuccess, when the UI should wait for fresh data before the mutation counts as finished. Skip the await when you want the mutation to settle immediately and the list to update a moment later.

Mistakes to avoid

  • Calling refetch() on one query after a write and leaving other views of the same data stale

  • Using refetchQueries without type: "active" and fetching data for screens that are not mounted

  • Expecting invalidateQueries to fetch a disabled query; use refetch from useQuery for that

  • Mutating the object inside setQueryData instead of returning a new one

  • Writing keys by hand in several places so the invalidation prefix misses some of them; keep keys in one factory

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Build a mini React Query: QueryClient, useQuery, prefix invalidation and garbage collectionHard60 min
  2. Build a TanStack Query-style useMutation(): lifecycle callbacks, optimistic updates, rollback and invalidationMedium50 min
  3. Implement TanStack Query's key helpers and structural sharing: hashKey, partialMatchKey and replaceEqualDeepMedium40 min
  4. Implement useQuery() with caching, retries, and stale dataMedium45 min
  5. Build RTK Query-style cache tags: providesTags, invalidatesTags and refetching only subscribed queriesMedium50 min