Cache invalidation marks locally cached remote data as no longer valid after a mutation, deferring the next server fetch until that data is needed. This avoids repeatedly refetching a complete list during rapid successive operations. section 9.3
Use query keys to invalidate the narrowest affected data:
- Give related queries a shared prefix, such as ["customers"], so invalidating that prefix refreshes customer lists and their parameterized variants. section 9.3.2
- Include distinguishing parameters—such as an ID, page, or name—in the query key. section 9.3.2
- After deleting a customer, invalidate both the customer-list prefix and the individual customer key, while leaving unrelated individual-customer caches available. section 9.3.2
Invalidate after a successful mutation
With TanStack Query, attach invalidation to onSuccess: call queryClient.invalidateQueries({ queryKey: ["customers"] }) for affected lists, then invalidate ["customer", { id }] for the deleted record. The mutation remains responsible for changing server data; invalidation coordinates subsequent reads. section 9.3.2
import {
useQueryClient,
useMutation,
} from "@tanstack/react-query";
function DeleteCustomer({ id }) {
const queryClient = useQueryClient();
const onSuccess = () => {
queryClient.invalidateQueries({ #1
queryKey: ["customers"], #1
}); #1
queryClient.invalidateQueries({ #2
queryKey: ["customer", { id }], #2
); #2
};
const deleteMutation = useMutation({
mutationFn: deleteCustomerById,
onSuccess,
});
return <button onClick={() => deleteMutation.mutate(id)}>Delete</button>;
}
Runnable React/TanStack Query code showing query-client access, deletion, and targeted invalidation. section 9.3.2
Invalidation is one part of a broader caching policy. TanStack Query can also refetch live queries after network recovery or window refocus, refetch stale queries on a configured interval, deduplicate identical requests, and retry failed requests. section 9.3.4

