useMutation Basics
You'll learn how to use the useMutation hook to perform server-side changes (creates, updates, deletes) with automatic tracking of loading, error, and success states.
What Is useMutation?
While useQuery is designed for reading data, useMutation handles writing data. Think of it like the difference between viewing your bank balance (query) versus making a transfer (mutation). Mutations change something on the server—creating a user, updating a profile, deleting a post—and TanStack Query needs to track these operations differently than reads.
Unlike useQuery, which executes automatically, useMutation gives you a trigger function that you call when ready (usually in response to a button click or form submission).
The Basic API
import { useMutation } from '@tanstack/react-query';
function CreatePost() {
const mutation = useMutation({
mutationFn: (newPost) => {
return fetch('/api/posts', {
method: 'POST',
body: JSON.stringify(newPost),
headers: { 'Content-Type': 'application/json' }
}).then(res => res.json());
}
});
const handleSubmit = (e) => {
e.preventDefault();
mutation.mutate({ title: 'My Post', body: '...' });
};
return (
<form onSubmit={handleSubmit}>
<button disabled={mutation.isPending}>
{mutation.isPending ? 'Creating...' : 'Create Post'}
</button>
{mutation.isError && <p>Error: {mutation.error.message}</p>}
{mutation.isSuccess && <p>Post created!</p>}
</form>
);
}
The hook returns an object with:
mutate(): Function to trigger the mutationisPending: True while the request is in-flightisError/isSuccess: Status flagserror/data: The error or response data
Key Takeaway: useMutation provides a controlled way to trigger server changes with automatic state tracking, giving you isPending, isError, and isSuccess flags without manual state management.