Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Mutations

Invalidating Queries After Mutations

Keep the screen in sync after a write: invalidateQueries, key prefixes and filters, returning the promise to await the refetch, and when not to refetch.

You add a todo. The server now has four todos, but your list still shows three, because the list is cached and nothing told it to change. The most common way to fix this is invalidation: after the mutation succeeds, you tell Query that certain cached data is out of date, and it refetches the ones that are on screen. This one pattern covers a large share of real applications.

What invalidation does

queryClient.invalidateQueries({ queryKey }) finds every query matching the key (by prefix) and does two things:

  1. Marks it as stale, regardless of its staleTime.
  2. If it is active (a mounted component observes it), refetches it right away.

Queries nobody is watching are only marked stale. They refetch the next time a component mounts and uses them. This is efficient: you never refetch data that no one can see.

The standard pattern

JSX
function AddTodo() {
  const queryClient = useQueryClient();

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

  // ...
}

Run the whole loop: a list, an add button, and a fake server that stores todos in memory.

Add a todo, then invalidate the list

Type a title and press Add. The mutation runs, then invalidateQueries triggers a refetch of ["todos"], and the new item appears. The server remains the source of truth, so what you see is what it actually stored.

Return the promise to keep the mutation pending

Look at the onSuccess above: it returns the promise from invalidateQueries. That has a visible effect. A mutation stays in the pending state until the promise returned by its onSuccess settles, so the button stays disabled until the list has refreshed. Without the return, the button re-enables as soon as the POST finishes, while the list is still catching up.

JSX
// Mutation stays pending until the refetch is done
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),

// Mutation completes immediately; the refetch continues in the background
onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["todos"] }); },

Choose based on the feel you want. Waiting is good for forms (the user sees a finished state), fire-and-forget is good for quick toggles.

Choosing what to invalidate

Because matching is by prefix, the key structure decides how much you refetch (see Query Keys).

JavaScript
// Everything about todos: lists, details, comments...
queryClient.invalidateQueries({ queryKey: ["todos"] });

// Only lists, not individual todo details
queryClient.invalidateQueries({ queryKey: ["todos", "list"] });

// Exactly one entry
queryClient.invalidateQueries({ queryKey: ["todos", "detail", 5], exact: true });

// A predicate for anything custom
queryClient.invalidateQueries({
  predicate: (query) => query.queryKey[0] === "todos" && query.state.data?.length > 100,
});

After updating todo 5, you probably want to invalidate that detail entry and every list that might contain it. Two calls, or one broad call on ["todos"], are both reasonable. A little over-fetching is almost always cheaper than showing stale data.

Filters worth knowing

Filter Effect
queryKey Prefix match
exact Only this exact key
type "active", "inactive" or "all" (default)
stale Match only stale (or only fresh) queries
fetchStatus "fetching", "paused", "idle"
predicate Your own function

Options for the refetch itself go in a second argument: invalidateQueries(filters, { cancelRefetch: false }). By default, an in-flight request is cancelled and restarted, because the data it is bringing may already be outdated.

Invalidate without refetching

Sometimes you want to mark data stale but not request it now, perhaps because the user is on another screen:

JavaScript
queryClient.invalidateQueries({ queryKey: ["todos"], refetchType: "none" });

refetchType can be "active" (default), "inactive", "all" or "none". With "none", queries are marked stale only, and they refresh the next time they are used.

Errors and settled callbacks

If the mutation fails, onSuccess does not run, so nothing is invalidated. That is usually right. But when you use optimistic updates, you must refetch in both cases to realign with the server, so you put the invalidation in onSettled, which runs on success and on failure:

JSX
useMutation({
  mutationFn: createTodo,
  onSettled: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
});

When invalidation is not the best tool

Refetching costs a request. If the mutation response already contains the new data, you can write it straight into the cache and skip the extra round trip. That technique, setQueryData, is the subject of Updating the Cache from Responses. Invalidate when the effect of a change is hard to predict on the client (sorting, counts, computed fields, other users' data). Write to the cache when the server hands you the exact new object.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does invalidateQueries do to an active query?

    Active queries are refetched immediately. Inactive ones are only marked stale and refresh on next use.
  2. 2. Why return the invalidateQueries promise from onSuccess?

    Query waits for the promise returned by onSuccess before settling the mutation, so isPending stays true until the data is fresh.
  3. 3. Which call invalidates todo lists but not details, given keys like ['todos','list',{...}] and ['todos','detail',5]?

    The prefix ['todos','list'] matches all lists only.
  4. 4. Which callback runs on both success and failure?

    onSettled always runs at the end, which makes it the right place to resync with the server.

Summary

  • Invalidation marks matching queries stale and refetches the active ones.
  • Put it in onSuccess (or onSettled) of the mutation, using a key prefix that covers the affected queries.
  • Return the promise to keep the mutation pending until the data is refreshed.
  • Use exact, type, predicate and refetchType to control the scope.
  • When the response contains the new data, consider writing it to the cache instead of refetching.

Next: Mutation Callbacks