Sub topic 13
Updating server data with mutations
Reading data and changing data are different jobs. A query reads server state and can run many times without harm. A mutation changes server state, such as creating, updating, or deleting a record, so it should run only when the user asks for it. This chapter shows how TanStack Query models that difference and how to keep the screen in sync after a change.
Prerequisites
This chapter assumes you know the following:
- How
useQueryworks, including query keys and the cache from the previous chapters. - Promises,
async/await, and HTTP methods such asPOST,PATCH, andDELETE. - The
useStatehook and basic JSX event handlers. - That your app is wrapped in a
QueryClientProvider.
Queries versus mutations
A query declares what data a component needs. TanStack Query decides when to run it: on mount, on window focus, after a key change, or on a retry. A mutation is imperative. Nothing happens until your code calls mutate.
| Aspect | Query (`useQuery`) | Mutation (`useMutation`) |
|---|---|---|
| Purpose | Read server data | Create, update, or delete server data |
| Runs | Automatically | Only when you call `mutate` |
| Cached by key | Yes | No |
| Retries on failure | Yes, by default | No, by default |
| Typical HTTP method | `GET` | `POST`, `PUT`, `PATCH`, `DELETE` |
Mutations do not retry by default because repeating a non-idempotent request, such as POST /orders, could create duplicate records.
A basic mutation
useMutation takes a mutationFn. That function receives the variables you pass to mutate and returns a promise. The hook returns an object that tracks the request, much like the loading, error, and success states you built by hand earlier.
import { useMutation, useQueryClient } from '@tanstack/react-query';
function RenameUser({ userId }) {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: async (name) => {
const response = await fetch(`/api/users/${userId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['user', userId] });
},
});
return (
<button onClick={() => mutation.mutate('Ada')} disabled={mutation.isPending}>
Rename
</button>
);
}Three details matter here.
- The
mutationFnchecksresponse.okand throws.fetchonly rejects on network failure, so without this check a400or500response would count as success. mutate('Ada')passes'Ada'as the single argument tomutationFn. To send several values, pass one object, such asmutate({ name, email }).disabled={mutation.isPending}stops the user from sending the same request twice while one is in flight.
The mutation state
The object returned by useMutation exposes the request status. These fields are the ones you will use most.
| Field | Meaning |
|---|---|
| `isPending` | The request is in flight. |
| `isError` and `error` | The last call failed, and the thrown error. |
| `isSuccess` and `data` | The last call succeeded, and the value your function returned. |
| `isIdle` | `mutate` has not been called yet, or `reset` was called. |
| `reset()` | Returns the mutation to the idle state, clearing an old error. |
The status names changed across versions. In TanStack Query v5 the in-flight flag is isPending. In v4 it was isLoading. If your code uses the wrong name, the flag is undefined and the button will never disable.
Invalidating cached data
After a successful mutation, the cached copy of the user is out of date. The cache still holds the old name, so the screen would show it until something else triggers a refetch.
invalidateQueries fixes this. It marks every cached query that matches the key as stale. If a matching query is currently on screen, TanStack Query refetches it right away. If it is not on screen, it refetches the next time a component uses it.
Key matching is by prefix. This gives you control over how much to refresh.
// Refresh only one user.
queryClient.invalidateQueries({ queryKey: ['user', 42] });
// Refresh every query whose key starts with 'user', for any id.
queryClient.invalidateQueries({ queryKey: ['user'] });
// Refresh everything in the cache.
queryClient.invalidateQueries();Invalidate the narrowest key that covers the data you changed. If you rename a user, the list of users probably shows that name too, so you may need to invalidate both ['user', userId] and ['users'].
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['user', userId] });
queryClient.invalidateQueries({ queryKey: ['users'] });
},The diagram shows the full cycle.
Waiting for the refetch
By default, onSuccess does not wait for the refetch. The mutation counts as finished as soon as onSuccess returns. If you return the promise from invalidateQueries, the mutation stays pending until the refetch completes.
onSuccess: () => {
return queryClient.invalidateQueries({ queryKey: ['user', userId] });
},Do this when you want the button to stay disabled until the screen shows the new data. Skip it if a brief moment of old data is acceptable.
Callbacks and where to put them
You can pass callbacks in two places, and they behave differently.
function RenameForm({ userId }) {
const queryClient = useQueryClient();
const [name, setName] = useState('');
const mutation = useMutation({
mutationFn: (newName) => renameUser(userId, newName),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['user', userId] });
},
});
function handleSubmit(event) {
event.preventDefault();
mutation.mutate(name, {
onSuccess: () => setName(''),
onError: (error) => console.error(error),
});
}
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button disabled={mutation.isPending}>Save</button>
{mutation.isError && <p role="alert">{mutation.error.message}</p>}
</form>
);
}Callbacks on useMutation always run, even if the component has unmounted. Put cache work there, such as invalidation. Callbacks passed to mutate run only if the component is still mounted when the request finishes. Put UI work there, such as clearing a field or navigating away.
This example assumes a renameUser helper that performs the PATCH request and throws on a non-2xx response, as in the previous example. It also needs useState imported from react.
Optimistic updates
Invalidation shows the new value only after two round trips: the mutation and the refetch. An optimistic update changes the cached value immediately, before the server replies, and rolls back if the request fails. It makes the interface feel instant, but you take on the work of undoing the change.
const mutation = useMutation({
mutationFn: (newName) => renameUser(userId, newName),
onMutate: async (newName) => {
await queryClient.cancelQueries({ queryKey: ['user', userId] });
const previous = queryClient.getQueryData(['user', userId]);
queryClient.setQueryData(['user', userId], (old) => ({ ...old, name: newName }));
return { previous };
},
onError: (error, newName, context) => {
queryClient.setQueryData(['user', userId], context.previous);
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['user', userId] });
},
});Each step has a reason.
cancelQueriesstops an in-flight refetch of the same data. Otherwise its older response could land after your optimistic write and overwrite it.getQueryDatasaves a snapshot.onMutatereturns it, and TanStack Query passes it toonErrorandonSettledascontext.setQueryDatawrites the guessed result into the cache. Every component using that key re-renders at once.onErrorrestores the snapshot if the server rejects the change.onSettledruns on success and on failure. Invalidating there replaces your guess with the real server value either way.
Always return a new object from setQueryData. Mutating old in place can prevent components from re-rendering.
Common errors
- Forgetting to throw on non-2xx responses. The mutation reports success,
onSuccessruns, and the screen refreshes with unchanged data. - Calling
mutateduring render. This sends a request on every render. Call it only from event handlers or effects that you control. - Invalidating the wrong key. The key must match the one used in
useQuery.['user', '42']and['user', 42]are different keys because one holds a string and the other a number. - Expecting retries. A failed mutation stays failed. Set the
retryoption only for idempotent requests. - Using stale closures. Values captured in
mutationFncome from the render that created it. Pass changing values throughmutate(variables)instead. - Forgetting
cancelQueriesin optimistic updates. A late refetch can erase the optimistic value and cause a visible flicker.
Exercise
A user renames a profile. The request returns status 200, but the page still shows the old name until the user reloads. The mutation code has no onSuccess callback. What is missing, and which key should it invalidate if the profile query uses useQuery({ queryKey: ['user', userId], ... })?
Show answer
The cache still holds the old data, so the code needs an onSuccess callback that calls queryClient.invalidateQueries({ queryKey: ['user', userId] }). That marks the cached user stale and refetches it because it is on screen. The key must match the query key exactly, including the type of userId.
Exercise
In an optimistic update, why does onMutate return the previous cache value, and where does the code use it?
Show answer
The returned value becomes context. If the request fails, onError receives context and calls setQueryData with context.previous to restore the data shown before the optimistic change.