React
Mutations
Learn to change data with useMutation.
What is useMutation?
useMutation is used for data-changing operations (POST, PUT, DELETE). It is triggered with the mutate function; on success onSuccess runs.
Typical usage: submit a form, write data to the server, then invalidate the cache. This refreshes the cache.
queryClient.invalidateQueries reruns the related queryKeys so the list shows the new data.
invalidateQueries
When a mutation succeeds, the cache needs to be updated. The call queryClient.invalidateQueries({ queryKey: ['users'] }) reruns every query with that key.
This makes new data arrive automatically; you do not need to write a manual refetch. The list refreshes right after the mutation.
invalidateQueries marks both active and inactive queries; active ones refetch immediately.
Exercise AddProduct with useMutation
Complete the skeleton. Write an AddProduct component. Call useMutation with mutationFn (newProduct) => fetch('/api/products', { method: 'POST', body: JSON.stringify(newProduct) }). In onSuccess call queryClient.invalidateQueries({ queryKey: ['products'] }). Render <button onClick={() => mutate({ name: 'Pen' })}>Add</button>. Get the client with const queryClient = useQueryClient(). Add export default.
Show example solution
import { useMutation, useQueryClient } from '@tanstack/react-query';
function AddProduct() {
const queryClient = useQueryClient();
const { mutate } = useMutation({
mutationFn: (newProduct) =>
fetch('/api/products', {
method: 'POST',
body: JSON.stringify(newProduct),
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['products'] });
},
});
return <button onClick={() => mutate({ name: 'Pen' })}>Add</button>;
}
export default AddProduct;
Test yourself
-
When do you use useMutation?
Writing data = useMutation.
- When reading data
- Only when changing CSS
- When changing data (POST/PUT/DELETE)
- Only when debugging
Show answer
When changing data (POST/PUT/DELETE) — useMutation is used to change data.
-
invalidate call
queryClient.____({ queryKey: ['users'] });
Show answer
queryClient.invalidateQueries({ queryKey: ['users'] });
-
Mutations: match the terms
- useMutation
- Changes data
- mutate
- Trigger function
- onSuccess
- After success
- invalidateQueries
- Refreshes cache
Next lesson: Summary - Data fetching