Skip to content
jshacks.dev
Frameworks

Invalidate queries after a mutation with TanStack Query

Refetch a cached list after a write by calling invalidateQueries in the onSuccess of useMutation, so the screen matches the server.

1 min read
Summarize in AI

You add a todo and the list still shows the old data. After a mutation, mark the related queries stale so they refetch.

src/AddTodo.jsxJSX
import { useMutation, useQueryClient } from '@tanstack/react-query';

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

  const mutation = useMutation({
    mutationFn: (title) =>
      fetch('/api/todos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title }),
      }).then((res) => {
        if (!res.ok) throw new Error('Save failed');
        return res.json();
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });

  return (
    <button disabled={mutation.isPending} onClick={() => mutation.mutate('Write snippet')}>
      {mutation.isPending ? 'Saving…' : 'Add todo'}
    </button>
  );
}
Text
POST /api/todos            -> 201
GET  /api/todos            -> 200   (refetched, the list shows the new todo)

invalidateQueries({ queryKey: ['todos'] }) marks every query whose key starts with ['todos'] as stale. Those currently on screen refetch right away, and the rest refetch the next time they are used. onSuccess runs only if the request succeeded. See Invalidations from Mutations.

Return the invalidateQueries promise from onSuccess if you want the mutation to stay pending until the refetch finishes. For instant feedback, update the cache by hand with setQueryData instead.

Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.