Caching, invalidation, and mutations

Intermediate · 1 min

useMutation, invalidating queries with queryClient.invalidateQueries, and an introduction to optimistic updates and their rollback tradeoff.

Before thisTanStack Query fundamentals

PedroTech · 18 min · from 18:29

Caching, invalidation, and mutations

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by PedroTechReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • useMutation is for writes — create, update, delete — while useQuery is for reads. Mutations don't run automatically on render; you call mutate() or mutateAsync() in response to an event.
  • A successful mutation does not update the query cache by itself. You have to tell TanStack Query which cached queries are now out of date, usually with queryClient.invalidateQueries in the mutation's onSuccess callback.
  • Invalidating a query marks it stale and triggers a refetch for any component currently using it, which is the mechanism that gets your UI back in sync with the server after a write.
  • An optimistic update applies the mutation's expected result to the cache immediately, before the server has responded, so the UI feels instant instead of waiting on a round trip.
  • Optimism has a cost: if the mutation fails, you must roll the cache back to its previous value, which means capturing that previous value before you optimistically overwrite it.
  • Reaching for an optimistic update is a deliberate tradeoff, not a default — it's worth it when the mutation almost always succeeds and the perceived speed matters, and not worth the rollback complexity otherwise.

Reads and writes need different hooks

useQuery runs automatically, as part of render, because reading data is something a component does just by existing. Writing data is different — you don’t want a POST firing every time a component re-renders. TanStack Query gives writes their own hook, useMutation, which you trigger explicitly:

import { useMutation, useQueryClient } from "@tanstack/react-query";

function createTodo(text) {
  return fetch("/api/todos", {
    method: "POST",
    body: JSON.stringify({ text }),
  }).then((res) => res.json());
}

function NewTodoForm() {
  const queryClient = useQueryClient();
  const { mutate, isPending } = useMutation({
    mutationFn: createTodo,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["todos"] });
    },
  });

  function handleSubmit(e) {
    e.preventDefault();
    const text = new FormData(e.target).get("text");
    mutate(text);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="text" />
      <button disabled={isPending}>Add todo</button>
    </form>
  );
}

mutate fires mutationFn and nothing else happens automatically — which is the detail that trips people up first.

The todo list rendered elsewhere on the page, via useQuery({ queryKey: ["todos"], ... }), has no idea a new todo was just created. TanStack Query doesn’t guess which reads are related to which writes — that relationship only exists in your head, so you have to state it.

queryClient.invalidateQueries({ queryKey: ["todos"] }) is that statement. It marks every cache entry whose key matches ["todos"] as stale and, if a component is currently rendering one of them, triggers a refetch immediately. This is the same cache and the same staleness mechanism from the previous lesson — invalidation is just a way of forcing staleness right now instead of waiting for staleTime to expire.

It’s common to call invalidateQueries with a prefix rather than an exact key, so that ["todos"] also invalidates ["todos", { status: "done" }] and any other variant — one write can clear out every cached view of that resource at once.

Optimistic updates: speed now, cleanup later

Waiting for a mutation to round-trip before updating the UI is simple but feels slow for small, likely-to-succeed actions like toggling a checkbox. An optimistic update writes the expected result into the cache immediately, then reconciles with reality once the server responds:

const queryClient = useQueryClient();

const { mutate } = useMutation({
  mutationFn: toggleTodo,
  onMutate: async (id) => {
    await queryClient.cancelQueries({ queryKey: ["todos"] });
    const previous = queryClient.getQueryData(["todos"]);

    queryClient.setQueryData(["todos"], (old) =>
      old.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
    );

    return { previous };
  },
  onError: (_err, _id, context) => {
    queryClient.setQueryData(["todos"], context.previous);
  },
  onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ["todos"] });
  },
});

The checkbox flips the instant you click it. onMutate snapshots the current cache value before changing it; if the server rejects the mutation, onError restores that snapshot so the UI doesn’t lie to the user about what actually happened. onSettled refetches regardless of outcome, to make sure the cache ends up matching the server exactly.

That snapshot-and-rollback pair is the whole cost of going optimistic. It’s worth paying for actions that are fast, frequent, and almost always succeed — a like button, a checkbox — and usually not worth paying for a rare, high-stakes action like submitting a payment, where showing a brief loading state and waiting for a real answer is the more honest choice.

What the video covers

This lesson uses PedroTech’s crash course from 18:29 onward, after its earlier fetching and caching material (already covered in the previous lesson). From there it walks through an introduction to mutations, creating a post and invalidating the cache on success, and a dedicated optimistic-updates segment — in that order, matching this lesson’s structure closely. Watch for the live demo of the UI updating before the network call resolves; it makes the “speed now, reconcile later” idea concrete in a way static code doesn’t.

Where this fits

The next lesson is when you need global state, which draws the line between server state — now handled by this cache — and client state that genuinely needs a global store.

Check yourself

  1. 01After a useMutation call succeeds, does the component automatically show the new data without any extra code?

    No. A mutation only performs the write; it does not know which queries read related data. You have to explicitly invalidate the relevant query keys, usually inside onSuccess, so TanStack Query refetches them and the UI catches up.

  2. 02What does queryClient.invalidateQueries({ queryKey: ['todos'] }) actually do?

    It marks every cached query whose key matches ['todos'] (including keys that start with 'todos', like ['todos', { status: 'done' }]) as stale and triggers a refetch for any of them currently in use, which is how the cache gets back in sync with the server after a write.

  3. 03What is the defining tradeoff of an optimistic update?

    The UI updates immediately, before the server confirms anything, which makes the app feel instant; in exchange, the code must capture the prior cache value and be ready to roll back to it if the mutation ultimately fails, which is extra complexity you don't need with a plain, non-optimistic mutation.

  4. 04Why would you choose not to make a particular mutation optimistic?

    If the mutation can realistically fail in ways the user needs to see accurately, or the rollback logic would be complex relative to the benefit, showing a brief loading state and waiting for the real server response is simpler and safer than building and maintaining a rollback path.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark