Invalidating Queries
You'll learn how to programmatically mark cached queries as stale to trigger automatic refetches.
The Core Idea
You've seen how refetch() lets you manually re-run a query, but TanStack Query offers a more powerful pattern: invalidating queries. When you invalidate a query, you're telling the cache "this data is now outdated" without immediately fetching. TanStack Query then automatically refetches that data if any component is currently using it.
Think of it like marking milk in your refrigerator as expired. You don't throw it out immediately—but the next time someone reaches for it, they'll know to get fresh milk instead.
Using queryClient.invalidateQueries()
You access the QueryClient instance and call invalidateQueries() with a query key (or pattern):
import { useQueryClient } from '@tanstack/react-query';
function CreateTodoButton() {
const queryClient = useQueryClient();
const handleCreate = async () => {
await createTodo({ title: 'New task' });
// Mark all 'todos' queries as stale
queryClient.invalidateQueries({ queryKey: ['todos'] });
};
return <button onClick={handleCreate}>Add Todo</button>;
}
When you invalidate ['todos'], every query with that key prefix becomes stale. If a component is currently displaying that data, TanStack Query automatically refetches it. If no component is using it, it just marks the cache entry as stale for next time.
Why Invalidate Instead of Refetch?
Invalidation is smarter: it refetches only active queries. If you have 5 different todo queries cached but only one is being displayed, only that one refetches. With manual refetch(), you'd need to track and call each one individually.
Key Takeaway: queryClient.invalidateQueries() marks queries as stale by key pattern, triggering automatic refetches for any active queries—perfect for keeping data fresh after mutations without manual refetch calls.