Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Mutations

Updating the Cache from Responses

Write mutation responses straight into the cache with setQueryData and setQueriesData, use functional updaters safely, and decide between writing and invalidating.

Invalidation is simple and safe, but it costs a second request: the mutation returns the saved object, and then you ask the server for the same data again. When the response already contains what the screen needs, you can write it directly into the cache. The UI updates the instant the mutation succeeds, with no extra round trip. The tools for this are setQueryData, setQueriesData and getQueryData.

setQueryData

JavaScript
queryClient.setQueryData(["todo", 5], updatedTodo);

It replaces the cached data for that exact key. Every component observing the key re-renders with the new value, just as if a fetch had returned it. If the key does not exist yet, the entry is created.

The second argument can also be an updater function that receives the old value and returns the new one:

JavaScript
queryClient.setQueryData(["todos"], (old) => old.map((t) => (t.id === 5 ? updatedTodo : t)));

Updater rules, and they matter:

  • Never mutate old. Return a new array or object. Query uses reference comparison to decide whether anything changed, and a mutated object breaks that.
  • old can be undefined if the key has no data yet. Guard for it: (old = []) => [...old, newTodo].
  • Returning undefined from the updater means "do nothing", which is how you cancel an update conditionally.

Using the mutation response

In the typical "update one item" flow, the PUT returns the saved object. Write it to the detail entry, and patch it into the lists.

Update the cache from the mutation response

Tick a box. After about 400 ms the checkbox updates and the "list requests" counter still reads 1. The cache was patched from the response, and no second GET was needed. (The box changes only after the server answers, because this version is not optimistic. The Optimistic Updates chapter shows how to update first and confirm later.)

Updating many queries: setQueriesData

A change often affects several cached entries: the list for "open" todos, the list for "all" todos, the detail for todo 5. setQueriesData applies an updater to every query matching a filter:

JavaScript
queryClient.setQueriesData({ queryKey: ["todos", "list"] }, (old) =>
  old ? old.map((t) => (t.id === saved.id ? saved : t)) : old
);

Each matching query gets the updater applied separately. Unlike setQueryData, it does not create entries that do not exist. It only touches existing ones, which is what you want here.

Remember that if you change a todo from open to done, an "open only" list should no longer contain it, and a simple map-and-replace will leave it there. Once such filtering rules appear, either implement them in the updater or simply invalidate those lists.

getQueryData and getQueryState

To read from the cache without subscribing, use:

JavaScript
const todos = queryClient.getQueryData(["todos"]);       // data or undefined
const state = queryClient.getQueryState(["todos"]);      // status, dataUpdatedAt, error...

These are plain reads. They do not fetch, do not cause re-renders and never throw if the key is missing. Use them inside callbacks and event handlers, not as a replacement for useQuery in render.

Write or invalidate?

Situation Better choice
Response contains the complete, final object setQueryData
Response is just { ok: true } invalidateQueries
Change affects sorting, counts, filters, pagination invalidateQueries
Several lists would each need custom patching invalidateQueries
You also want to be sure of the server state Write and invalidate

Writing and invalidating together is a legitimate and common combination: patch the cache for an instant result, then invalidate in the background so the server's truth wins if anything differs.

JavaScript
onSuccess: (saved) => {
  queryClient.setQueryData(["todos", "detail", saved.id], saved);   // instant
  queryClient.invalidateQueries({ queryKey: ["todos", "list"] });   // lists re-sorted by the server
},

Data written to the cache is not a fetch

setQueryData sets dataUpdatedAt to now, so the entry counts as fresh for staleTime. It does not trigger a request and does not run select's source function. If the key has an active observer with a function that would produce a different shape, the next refetch will replace your data. Always write data in exactly the shape the queryFn returns; writing a different shape is a classic source of "it works until the next refetch" bugs.

getQueryData, setQueryData and getQueryState

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does setQueryData(['todo', 5], saved) do?

    It writes data into the cache without any request, and observers re-render.
  2. 2. Which updater is correct?

    Updaters must be immutable and must handle an undefined old value.
  3. 3. How is setQueriesData different from setQueryData?

    setQueriesData takes a filter and patches all matching queries.
  4. 4. When is invalidating better than writing to the cache?

    Server-side effects on ordering and filters are easier to refetch than to reproduce on the client.

Summary

  • setQueryData writes data into the cache; an updater function gets the previous value and must not mutate it.
  • setQueriesData patches every existing query that matches a filter.
  • getQueryData and getQueryState read the cache without fetching or subscribing.
  • Write to the cache when the response holds the final object; invalidate when effects are hard to predict; combine both for instant and correct.
  • Always write data in the same shape the queryFn returns.

Next: Mutation State and Scopes