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

setQueryData for Manual Cache Updates

Directly manipulate query cache with queryClient.setQueryData() for fine-grained optimistic or manual updates.

setQueryData for Manual Cache Updates

What you'll learn: How to directly modify TanStack Query's cache using setQueryData() for surgical, manual updates without refetching.


The Core Idea

While TanStack Query automatically manages cache updates through refetching and invalidation, sometimes you already know what the new data should be. Maybe you just created a new item, or updated one, and the mutation response tells you exactly what changed. Why trigger a refetch when you can surgically update the cache yourself?

queryClient.setQueryData() lets you directly write data into the cache for a specific query key. Think of it as reaching into the cache drawer and replacing a file yourself, rather than asking the system to go fetch it again.

When to Use It

Use setQueryData() when:

  • You receive updated data from a mutation response
  • You want to update a list after adding/removing items
  • You need fine-grained control beyond automatic invalidation
  • You want to avoid unnecessary network requests

Basic Usage Pattern

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

function useUpdateTodo() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: updateTodoAPI,
    onSuccess: (updatedTodo) => {
      // Directly update the single todo in cache
      queryClient.setQueryData(['todo', updatedTodo.id], updatedTodo);
      
      // Update the list by mapping over old data
      queryClient.setQueryData(['todos'], (oldTodos) => 
        oldTodos?.map(todo => 
          todo.id === updatedTodo.id ? updatedTodo : todo
        )
      );
    }
  });
}

The first argument is the query key, the second is either the new data or an updater function that receives the old data.

Key Takeaway: Use queryClient.setQueryData() to directly manipulate cached data when you already know the new value, eliminating unnecessary refetches and giving you precise control over cache updates.