Course contentsShow
← React
Lesson 1794 of 2,39642. Data Fetching LibrariesFree lesson

Invalidating Queries After Mutations

Trigger automatic refetches by invalidating query keys with queryClient.invalidateQueries() in mutation callbacks.

Invalidating Queries After Mutations

What you'll learn: How to automatically refetch fresh data after mutations by invalidating query keys with queryClient.invalidateQueries().

When you mutate data on the server (create, update, or delete), your cached queries become outdated. TanStack Query won't automatically know that server data has changed, so you need to tell it which queries are now "stale" and should be refetched.

The Problem

Imagine you fetch a list of todos with useQuery(['todos']), then add a new todo with useMutation. The server now has fresh data, but your UI still shows the old cached list. You need a way to trigger a refetch.

The Solution: Query Invalidation

Use the queryClient.invalidateQueries() method inside your mutation callbacks (typically onSuccess). This marks matching queries as stale and triggers an automatic refetch:

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

function TodoForm() {
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: createTodo,
    onSuccess: () => {
      // Invalidate and refetch any query with key ['todos']
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    }
  });

  // Now when you add a todo, the list automatically refreshes!
}

How It Works

When you call invalidateQueries(), TanStack Query:

  1. Marks all matching queries as stale
  2. Triggers an immediate refetch if those queries are currently active (rendered on screen)
  3. Ensures next render uses fresh data

Think of it like pressing "refresh" on your browser, but surgically targeted at specific pieces of data that you know changed.

Key Takeaway: Use queryClient.invalidateQueries() in mutation callbacks to automatically refetch queries after data changes, keeping your UI synchronized with server state without manual refetch calls.