What is `useMutation` and when would you use it?

Beginner

Answer

useMutation is used for operations that create, update, or delete data (side effects). Unlike useQuery, mutations don't run automatically and must be triggered manually.
Basic usage:

const mutation = useMutation({
  mutationFn: (newPost) => fetch('/api/posts', {
    method: 'POST',
    body: JSON.stringify(newPost)
  }),
  onSuccess: (data) => {
    // Invalidate and refetch related queries
    queryClient.invalidateQueries({ queryKey: ['posts'] });
  },
  onError: (error) => {
    console.error('Failed to create post:', error);
  }
});
// Trigger the mutation
const handleSubmit = (formData) => {
  mutation.mutate(formData);
};

Key properties:

  • mutationFn: Function that performs the mutation
  • onSuccess: Callback for successful mutations
  • onError: Callback for failed mutations
  • onSettled: Callback that runs regardless of success/failure
    Use cases:
  • Creating new records
  • Updating existing data
  • Deleting records
  • Any operation that modifies server state