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

Coordinating Multiple Mutations

Handle complex flows with dependent mutations, parallel mutations, or mutations that affect multiple query keys.

Coordinating Multiple Mutations

You'll learn how to handle complex scenarios where mutations depend on each other, run in parallel, or trigger multiple cache updates across your application.

The Challenge

Real-world mutations rarely happen in isolation. You might need to create a user and then upload their avatar, or delete multiple items in parallel, or update several related cache entries after a single mutation. TanStack Query mutations work independently by default—coordinating them requires intentional patterns.

Sequential Dependent Mutations

When one mutation depends on another's result, chain them in callbacks:

const createUser = useMutation({ mutationFn: postUser });
const uploadAvatar = useMutation({ mutationFn: postAvatar });

const handleSignup = async () => {
  createUser.mutate(userData, {
    onSuccess: (newUser) => {
      // Use the created user's ID for the avatar upload
      uploadAvatar.mutate({ userId: newUser.id, file: avatarFile });
    }
  });
};

The second mutation only fires after the first succeeds, using its returned data.

Parallel Independent Mutations

For unrelated mutations, trigger them simultaneously but coordinate their completion:

const deletePost = useMutation({ mutationFn: api.deletePost });
const deleteComment = useMutation({ mutationFn: api.deleteComment });

const handleBulkDelete = () => {
  deletePost.mutate(postId);
  deleteComment.mutate(commentId);
  // Both run in parallel
};

Check deletePost.isSuccess && deleteComment.isSuccess to know when both finish.

Multi-Cache Invalidation

A single mutation often affects multiple query keys:

const updateProfile = useMutation({
  mutationFn: patchProfile,
  onSuccess: (data) => {
    queryClient.invalidateQueries({ queryKey: ['user', data.id] });
    queryClient.invalidateQueries({ queryKey: ['users'] }); // List view
    queryClient.invalidateQueries({ queryKey: ['notifications'] }); // Might change
  }
});

Key Takeaway: Coordinate mutations through callbacks for sequences, trigger parallel mutations independently while tracking their states, and invalidate all affected cache keys to keep your UI consistent across components.