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 mutationonSuccess: Callback for successful mutationsonError: Callback for failed mutationsonSettled: Callback that runs regardless of success/failure