Mutations with useMutation and Cache Invalidation
Use useMutation to POST data, invalidate related queries on success so the list refreshes automatically, and display optimistic UI feedback while the request is in flight.
What Is a Mutation?
In React Query terminology, a mutation is any operation that changes server data — POST, PUT, PATCH, or DELETE requests. While useQuery fetches and caches data, useMutation handles data modification with loading, error, and success states, plus powerful side-effect callbacks.
Separating queries (reads) from mutations (writes) is a key conceptual pattern. Mutations don't cache their results — they trigger side effects and then cause related queries to refetch fresh data.
useMutation Basics
useMutation takes a mutationFn — an async function that performs the write operation. It returns a mutate function (or mutateAsync for Promise-based usage) that you call when the user triggers the action.
Unlike useQuery, mutations don't run automatically. They wait for you to call mutate(variables). The hook provides isPending, isError, isSuccess, error, and data state from the mutation's response.
import { useMutation } from '@tanstack/react-query';
async function createPost(newPost) {
const response = await fetch('https://api.example.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newPost),
});
if (!response.ok) throw new Error('Failed to create post');
return response.json();
}
const { mutate, isPending, isError } = useMutation({
mutationFn: createPost,
});All lessons in this course
- QueryClient, QueryClientProvider, and useQuery
- Mutations with useMutation and Cache Invalidation
- Persisting the Query Cache with AsyncStorage
- Background Refetch and Stale Time Configuration