Mutations and optimistic UI
Overview
Reading data is half the job. The other half is changing it: enrolling in a course, posting a comment, deleting a lesson. These are mutations. Doing them well means three things: tracking pending and error states, making sure every part of the UI shows the new data afterwards, and — for small, likely-to-succeed actions — updating the screen before the server even answers.
Mutations with TanStack Query
import { useMutation, useQueryClient } from '@tanstack/react-query';
async function enrol(courseId) {
const res = await fetch('/api/enrolments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ courseId }),
});
if (!res.ok) throw new Error('Enrolment failed');
return res.json();
}
function EnrolButton({ courseId }) {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: enrol,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['enrolments'] });
queryClient.invalidateQueries({ queryKey: ['courses', courseId] });
},
});
return (
<>
<button onClick={() => mutation.mutate(courseId)} disabled={mutation.isPending}>
{mutation.isPending ? 'Enrolling…' : 'Enrol'}
</button>
{mutation.isError && <p role="alert">{mutation.error.message}</p>}
{mutation.isSuccess && <p role="status">You’re in! 🎉</p>}
</>
);
}useMutationdoesn’t run anything until you callmutate(variables)(orawait mutateAsync(variables)).- It tracks
isPending,isError,error,isSuccessanddata. - Mutations are not retried by default — repeating a POST could create duplicates.
Invalidation
After enrolling, the “My courses” list and the course’s seat count are out of date. invalidateQueries marks matching queries as stale and refetches any that are on screen. Keys match by prefix, so { queryKey: ['courses'] } invalidates ['courses'], ['courses', 7] and ['courses', { q: 'react' }].
Invalidation is the simplest correct approach: let the server tell you the new truth. If the mutation’s response already contains the updated object, you can write it straight into the cache instead and save a request:
onSuccess: (updatedCourse) => {
queryClient.setQueryData(['courses', updatedCourse.id], updatedCourse);
},Optimistic UI
Some actions almost always succeed — liking a post, ticking off a lesson, starring a course. Waiting 300 ms for the server before showing the change makes the app feel sluggish. Optimistic UI updates the screen immediately and reconciles with the server afterwards:
useOptimistic
React 19’s useOptimistic hook shows a temporary value while an action is in progress:
import { useOptimistic, useState, startTransition } from 'react';
function LessonCheckbox({ lesson, saveCompleted }) {
const [completed, setCompleted] = useState(lesson.completed);
const [optimisticCompleted, setOptimisticCompleted] = useOptimistic(completed);
function handleChange(e) {
const next = e.target.checked;
startTransition(async () => {
setOptimisticCompleted(next); // shows immediately
await saveCompleted(lesson.id, next); // server request
startTransition(() => setCompleted(next)); // confirm
});
}
return (
<label>
<input type="checkbox" checked={optimisticCompleted} onChange={handleChange} />
{lesson.title}
</label>
);
}How it works:
useOptimistic(state)returns[optimisticState, setOptimistic]. When no action is pending,optimisticStateisstate.- Inside an action (a transition or form action), calling
setOptimisticshows the temporary value immediately. - When the action finishes, React drops the optimistic value and shows the real
stateagain. If you updatedstate(success), the UI keeps the new value. If the request threw and you didn’t update it (failure), the UI automatically rolls back.
You can pass a reducer to combine the current state with an optimistic change — perfect for lists:
const [optimisticComments, addOptimisticComment] = useOptimistic(
comments,
(current, newComment) => [...current, { ...newComment, pending: true }]
);
async function postAction(formData) {
const text = formData.get('text');
addOptimisticComment({ id: crypto.randomUUID(), text });
const saved = await postComment(text);
startTransition(() => setComments((c) => [...c, saved]));
}
// render: style comments with `pending: true` more faintly
<form action={postAction}>…</form>Show pending items slightly faded or with a “Sending…” label, so users know they aren’t confirmed yet.
Note: state updates after an
awaitinside a transition need their ownstartTransitionwrapper to be part of the transition — that’s why the examples wrapsetCompletedandsetComments.
Optimistic updates with TanStack Query
When the data lives in TanStack Query’s cache, update the cache itself optimistically:
const queryClient = useQueryClient();
const toggleLesson = useMutation({
mutationFn: ({ id, completed }) => saveCompleted(id, completed),
onMutate: async ({ id, completed }) => {
await queryClient.cancelQueries({ queryKey: ['lessons'] });
const previous = queryClient.getQueryData(['lessons']);
queryClient.setQueryData(['lessons'], (old) =>
old.map((l) => (l.id === id ? { ...l, completed } : l))
);
return { previous }; // context for rollback
},
onError: (err, variables, context) => {
queryClient.setQueryData(['lessons'], context.previous); // roll back
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['lessons'] }); // resync with the server
},
});onMutatecancels in-flight refetches (so they don’t overwrite the optimistic data), snapshots the current data and writes the optimistic version.onErrorrestores the snapshot.onSettledrefetches to make sure the cache matches the server either way.
When not to be optimistic
Optimistic UI suits frequent, low-risk, easily reversible actions. Don’t use it for:
- payments and purchases,
- actions that often fail validation on the server,
- irreversible actions (deleting an account),
- anything where showing success and then reverting would mislead the user.
For those, show a clear pending state and wait for the server.
Always handle failure. An optimistic update that silently reverts confuses users. Show a short message — “Couldn’t save — please try again” — when you roll back.
An optimistic like button
Write LikeButton({ initialLikes, likePost }) using useState for the confirmed count and useOptimistic for the displayed count. On click, start a transition that adds 1 optimistically, awaits likePost() (which returns the new server count) and then stores the confirmed count. If likePost rejects, the count must return to its previous value and an error message “Couldn’t save your like” should appear.
import { useOptimistic, useState, startTransition } from 'react';
export function LikeButton({ initialLikes, likePost }) {
// your code here
}import { useOptimistic, useState, startTransition } from 'react';
export function LikeButton({ initialLikes, likePost }) {
const [likes, setLikes] = useState(initialLikes);
const [error, setError] = useState(null);
const [optimisticLikes, addOptimisticLike] = useOptimistic(likes, (current, delta) => current + delta);
function handleClick() {
setError(null);
startTransition(async () => {
addOptimisticLike(1);
try {
const serverCount = await likePost();
startTransition(() => setLikes(serverCount));
} catch {
setError('Couldn’t save your like');
// no setLikes: when the transition ends, optimisticLikes falls back to `likes`
}
});
}
return (
<>
<button onClick={handleClick}>♥ {optimisticLikes}</button>
{error && <p role="alert">{error}</p>}
</>
);
}Summary
useMutation({ mutationFn })runs create, update and delete requests and tracks their pending and error state.- After a mutation succeeds, invalidate related queries so they refetch:
queryClient.invalidateQueries({ queryKey }). - Optimistic UI shows the expected result immediately and rolls back if the request fails.
- React’s
useOptimisticshows a temporary value while an action is pending, then returns to the real state. - TanStack Query can also update the cache optimistically with
onMutate, rolling back inonError.