CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

App.jsx
import { useMutation, useQueryClient } from '@tanstack/react-query';

// Write AddProduct here

Sample solution

App.jsx
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;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When do you use useMutation?

App.jsx
Writing data = useMutation.
  • When reading data
  • Only when changing CSS
  • When changing data (POST/PUT/DELETE) Correct answer
  • Only when debugging

Explanation: useMutation is used to change data.

2 invalidate call

Question
queryClient.____({ queryKey: ['users'] });
Answer
queryClient.invalidateQueries({ queryKey: ['users'] });

Explanation: invalidateQueries refreshes the cache.

3 Mutations: match the terms

Term Meaning
useMutation Changes data
mutate Trigger function
onSuccess After success
invalidateQueries Refreshes cache

All lessons in Advanced