Change it now, confirm it later: optimistic UI updates in practice
A like that takes half a second to turn red gets tapped twice. This guide follows the TanStack Query and React official docs through optimistic updates: the variables and onMutate approaches, useOptimistic reducers and delete recovery, three levels of failure handling, concurrent temporary ids, and five anti-patterns, with a pre-ship checklist.

First, the boundaries. This site already has several guides about "making the interface move first," but none of them is this one. The in-app messaging guide covers how messages are sent and received, and mentions in passing that you should "show the message as soon as you hit send." This guide is the full method behind that one sentence: optimistic updates. The offline-sync guide and the multi-device conflict guide cover how data eventually merges; this one covers what the interface shows before the merge happens. The loading, empty, and error states guide covers what the interface looks like while waiting for data; this one covers the opposite — not waiting for the data, and showing the result first. Optimistic updates are not a replacement for loading states. They are a different road: the moment the user taps, the interface draws the screen as if it already succeeded, and the server's answer arrives a little later.
The "Buy Together" app used below is a fictional practice project: a few people share one shopping list, add items, like them, and check off what they have bought. Every action, code snippet, and number built around it in this article was invented to explain the method. It is not a real record. All rules, interface names, and behaviors for TanStack Query and React come from the two projects' official documentation; the sources are in each article's meta information and evidence record. Other frameworks have their own optimistic-update methods. The thinking is the same, but the interface names differ, so check that framework's own documentation before copying anything over.
What optimistic updates really are: an account of time
Start with an account of time. A user taps "like." The request travels from the phone to the server and back. On an ordinary network that takes 200 to 500 milliseconds; on a weak network it can reach 2 seconds. If you wait for the server to say "done" before turning the heart red, then for those 200 milliseconds to 2 seconds the user sees nothing happen. Tap once, nothing happens — most people will tap again. The server then gets two likes, the heart flips back, or a duplicate record appears. Optimistic updates do it the other way around: in the same millisecond as the tap, the interface turns the heart red and adds one to the count first; the request travels in the background, confirms quietly on success, and flips the heart back and tells the user it failed on failure.
This is not "tricking" the user. It is admitting a fact: the vast majority of these operations succeed. Liking, bookmarking, following, checking off a to-do, renaming something — these fail so rarely that it is not worth making every tap wait half a second first. Treat "draw the result first, wait for confirmation later" as the default, and "roll back on failure" as the exception, and the interface changes from "every step stalls a little" to "every step follows the finger." That feeling of responsiveness does not come from animation. It comes from timing: feedback happens the moment the user's finger leaves the screen, not the moment the server's response arrives.
But optimistic updates are not a cure-all. They only fix the "feedback is slow" problem, not the "the operation itself is slow" problem. Uploading a 20MB photo: the most an optimistic update can do is put the thumbnail up first and show "uploading"; the photo still takes its time to actually upload. Sending a message: an optimistic update can paste the message into the dialog first; the message still needs the server to actually deliver it. Keep these two layers apart and you will not expect too much from optimistic updates: they manage the layer the user "sees," not the layer where things get "done."

Four gates first: can this operation be optimistic?
Not every operation can be optimistic. Before you start, run the operation through four gates. If it fails any one of them, wait for the server like an honest person.
Gate one: can the result be worked out in advance? After a like, the heart is red and the count goes up by one — you know that without asking the server. Rename something, and you know what it will display as. But when the result has to be computed by the server first, you cannot be optimistic: claiming a coupon, for example — whether you get 20 off over 100 or 10 off over 50 is the server's call; so are search, recommendations, and price calculation. Results you cannot guess in advance should not be guessed.
Gate two: can a failure be explained? When the operation fails, you have to be able to tell the user "that tap didn't go through," and the user has to be able to accept that. A failed like flips the heart back and shows "Like failed, please retry" — users understand that. A failed follow is the same. But some failures cannot be explained away: the interface says "payment succeeded" and a moment later says "actually it didn't go through." No user accepts that kind of reversal.
Gate three: can the operation be tried again? Operations where the user can tap "retry" and do it over are a good fit for optimism. Likes, bookmarks, messages, editing a note — all of these. Irreversible operations are not: deleting an account, deactivating, wiping data, sending a verification code, charging money. Once the interface has "shown success first" for one of these, there is no clean way to take it back on failure.
Gate four: is the failure rate low enough? If an operation fails three times out of ten in your product, optimistic updates just slap the user in the face over and over: red, then not red, added, then gone. Fix the success rate first, then talk about optimism. If gate four fails, passing the first three does not help.
Remember one hard line: anything involving money, irreversible deletion, or legal effect is never optimistic. Paying, refunding, deleting an account, unbinding a phone number, submitting identity verification — even if they are slower and spin longer, wait for the server to nod. An interface that is half a second slow earns at most a complaint; an interface that says "success" first and takes it back later makes the user feel cheated.
Road one: two ways to do it in TanStack Query
If you use TanStack Query (also known as React Query), the official documentation gives you two ways to write optimistic updates. The first is the simplest: use the variables returned by useMutation directly. While the like mutation is still running, variables already holds the data that was passed to this mutation, so when you render the list you can append one extra temporary, semi-transparent item. When the mutation finishes, the temporary item disappears by itself — if the server says success and the list is refetched, the real item shows up in its normal style; if it failed, the temporary item disappears too, and you can use the mutation's isError state to keep showing that failed piece of data with a "retry" button next to it.
The biggest advantage of this approach is that you never have to think about rolling back. The temporary item was never really written into the cache; it is only "one extra item drawn while the mutation is running." The moment the mutation ends, success or failure, it is gone. The cost is that it works most smoothly when the mutation and the list live in the same component. The official documentation says so directly: if the mutation and the list live in different components, you can use the useMutationState hook to read all in-flight mutations from another component, combined with a mutationKey. variables will then be an array, because several mutations may be running at the same time. If you need a unique key for each optimistic item, you can use mutation.state.submittedAt — tapping twice in a row will not produce a collision.
The second approach updates the cache directly, and it fits the case where "several places on the screen all have to change together": after a like, the number in the list, the number on the detail page, and the stats on the profile page all have to go up by one. The way to do it is to pass onMutate to useMutation: before the request goes out, change the cached data into its optimistic shape. The official documentation recommends having onMutate return a value — usually a rollback function — which is then passed unchanged to onError and onSettled. If the request fails, call that rollback function inside onError to restore the cache to how it was before the request; whether the request succeeds or fails, refetch the data inside onSettled so the cache lines up with the server again.
// onMutate updates the cache first and returns a rollback function;
// onError uses it to restore the old data on failure
useMutation({
mutationFn: toggleLike,
onMutate: async (postId) => {
await queryClient.cancelQueries({ queryKey: ["post", postId] });
const previous = queryClient.getQueryData(["post", postId]);
queryClient.setQueryData(["post", postId], (old) => ({
...old,
liked: !old.liked,
likes: old.likes + (old.liked ? -1 : 1),
}));
return { rollback: () => queryClient.setQueryData(["post", postId], previous) };
},
onError: (_err, _vars, context) => context?.rollback(),
onSettled: (_data, _err, postId) =>
queryClient.invalidateQueries({ queryKey: ["post", postId] }),
});
The official documentation also includes a very practical reminder: in most failure scenarios you do not need to hand-write a rollback at all — just trigger a refetch, and the cache goes back to the true server state. A hand-written rollback is only required in one situation: when the failure itself means the server is having trouble and even a refetch cannot get the data back. Then a refetch cannot fetch the truth, and only the old data you saved beforehand can restore the interface. So write the rollback function, but do not treat it as your only lifeline — refetch first, roll back only if the refetch fails. Do not reverse that order.
How do you choose between the two approaches? The official documentation gives a very direct rule: if only one place needs to show the optimistic result, use variables — less code, no rollback to manage, and the easiest to reason about. If several places all have to change, update the cache directly: change it once and the whole screen lines up. Choosing wrong is not a disaster either: start with variables, and when a second place genuinely needs to change too, switch to onMutate. The refactor is small.
Road two: React's built-in useOptimistic
If you use React 19, the official docs offer another road: the useOptimistic hook. It does not touch any cache; it only manages "what this component shows while an Action is running." The signature is short: const [optimisticState, setOptimistic] = useOptimistic(value, reducer?). The first argument is the real value; the second is an optional reducer. When no Action is pending, it returns the real value; while an Action is running, it returns the optimistic value computed by the reducer.
The simplest use is a like button. The real isLiked lives in the parent component's state, and the button wraps it in useOptimistic(isLiked). On click, inside startTransition, first call setOptimisticIsLiked(!optimisticIsLiked), then await toggleLike(newValue), and once the server answers, update the real isLiked. What if it fails? The official documentation is clear: if the Action throws, the Transition still ends and React re-renders with whatever the real value currently is. Since the parent normally only updates the real value on success, a failure means the value has not changed, so the interface automatically goes back to how it looked before the like. All you need to do is catch the error and show the user a message. The rollback is done for you by the framework.
There are two iron rules here, and breaking either one errors out directly. First, setOptimistic must be called inside a Transition or an Action. Calling it outside produces the error "An optimistic state update occurred outside a Transition or Action," and the optimistic value only flashes briefly before snapping back. Calling it inside startTransition(async () => {...}) is correct, as is calling it inside a form's Action prop — props that by convention end in "Action" already run inside a Transition. Second, you cannot call the setter while rendering; doing so produces "Cannot update optimistic state while rendering." The setter may only appear in event handlers, effects, or other callbacks.
List scenarios need a reducer. The official documentation's to-do list example looks like this: useOptimistic(todos, (currentTodos, newTodo) => [...currentTodos, { ...newTodo, pending: true }]). When adding, the new item first gets a pending: true flag, and the render appends "Adding..." after it. The reason for using a reducer instead of passing a function directly is practical: if another user adds an item while your Action is still running and the todos prop changes, React re-runs your reducer with the new todos, so your optimistic item lands on top of the latest list rather than an outdated copy. An updater function passed directly cannot see that change — it only knows the state from the moment the Transition started.
// Follow button: two values change together, so one reducer computes both
// at once and the button text and follower count always stay in sync
const [optimisticState, updateOptimistic] = useOptimistic(
{ isFollowing: user.isFollowing, followerCount: user.followerCount },
(current, isFollowing) => ({
isFollowing,
followerCount: current.followerCount + (isFollowing ? 1 : -1),
})
);
function handleClick() {
const next = !optimisticState.isFollowing;
startTransition(async () => {
updateOptimistic(next);
await followAction(next);
});
}
One reducer can also handle several kinds of action. The official documentation's shopping-cart example uses a single reducer with an action object carrying a type field to handle three actions: add adds one item (if it is already in the cart, the quantity goes up by one), remove deletes the whole row, and update_quantity changes the quantity. Each action marks the item pending: true, and the total is computed straight from the optimistic cart. Three actions sharing one reducer means "what the cart looks like" is decided in exactly one place, instead of being written three different ways in three handlers.
Deleting is the kind of optimistic update that needs the most care. The official documentation has a dedicated example, "optimistic delete with error recovery": clicking delete does not remove the row from the list right away. Instead it first marks the item deleting: true, rendering it semi-transparent with a strikethrough, and the button text becomes "Deleting..." and is disabled. If the delete succeeds, the parent updates the real list and the item disappears naturally. If the delete fails, you catch the error and show the message, and the item reappears automatically because the real value never changed. Fading an item out first and letting it disappear later is far more honest — and easier for users to understand — than "gone in one tap, suddenly back again on failure."
When it fails: three levels of handling, not just one
Failure handling for optimistic updates comes in three levels, chosen by "can the user fix it themselves?" Level one is a quiet refetch: the failure is most likely a one-off network hiccup, the user does not even need to know it happened, and refetching the data once puts the interface back to its true state. Like counts, follow counts, bookmark states — data people glance at and move on from — use level one.
Level two is roll back plus one sentence: the operation failed, the interface returns to how it was, and next to where the operation happened you give one plain sentence — "Like failed, please retry" — not a full-screen error. The message should grow next to the operation, not at the top of the screen. Wherever the user tapped, that is where the message should appear. This level fits most cases where the user needs to know "that tap didn't go through."
Level three is keep it and offer a resend: the failed operation contains user input, and losing it would force the user to type it all over again — the most expensive outcome. Sending a message is the classic example: the message is pasted into the dialog first, and if sending fails, the message stays put, with a "Send failed, tap to resend" button underneath it and the original text untouched. The rule for choosing this level is simple: if redoing it costs the user more than ten seconds, use level three; if one tap is enough to redo it, level two is enough.
There is one more thing that is easy to miss: when retrying, do not let the server execute the operation twice. If the user taps "retry" twice in a row, the server may receive two requests, turning one like into two or one order into two orders. The fix is to give every operation an idempotency key: no matter how many times the same operation is sent, the server only honors the first one. This site's agent-friendly API design guide already explains idempotency keys in full, so here is just the conclusion — a retry button on an optimistic update must come with an idempotency key, or the retry itself becomes a new bug.
Concurrency: rapid taps, out-of-order responses, and temporary ids
The easiest place for optimistic updates to go wrong is when the user's fingers are faster than the network. Tap the like button three times in a row: the first tap has not come back yet, but the second and third have already gone out. The three requests may not even return in the order they were sent — the first one sent can arrive last. If the interface only draws "whatever the last answer to arrive says," it can end up wrong: the user tapped three times — like, unlike, like — but the last answer to arrive belongs to the second tap, so the interface stops at "not liked," which does not match the user's third tap.
There are three fixes. First, give every operation a temporary id: a newly added item first takes a client-generated id (for example crypto.randomUUID()) as a placeholder, and the server's real id replaces it when the response arrives. Use that id as the list key when rendering — never use the array index as a key, because indexes shift after insertions and deletions, and optimistic items will no longer line up with real ones. Second, merge operations that cancel each other out: a run of like, unlike, like should only send the final state once, not send all three requests. Third, queue optimistic updates on the same object: do not send the next one until the previous one is confirmed, or send it with information about "which version this is based on" so the server can judge the order.
There is a subtler form of concurrency: two people editing the same thing at the same time. You change the quantity of "milk" on the list from 1 to 2, while someone else changes it to 3 at the same moment. Your optimistic update shows 2, theirs shows 3, and the server will only keep one of them. Whoever wins, the loser's interface has to quietly become the winner's number — but should you tell the user? The answer is: if the change is a small thing like a quantity, syncing quietly is fine; if it is a big thing like a whole paragraph of text or an entire configuration, ask the user first before syncing, or show the conflict and let them choose. Optimistic updates manage "show my operation first." Conflict resolution is a different guide's job — the multi-device conflict guide — so do not mix the two together here.
Five anti-patterns
Anti-pattern one: being optimistic about money. A pay button that shows "Payment successful" the moment it is tapped, then takes it back when the charge fails. That is not an experience optimization; it is gambling with the user's trust. Money, account deletion, unbinding, identity verification — all of them wait for the server to nod.
Anti-pattern two: optimistic deletion with no trace. Tap delete, the row vanishes instantly, and on failure it suddenly pops back — the user will think they saw a ghost. Delete should first fade the row out, add a strikethrough, and turn the button into "Deleting...". On failure the row stays where it was, with one sentence next to it explaining why.
Anti-pattern three: silently swallowing failures. The request fails, the interface quietly flips back, and nothing is said. The user clearly tapped "like," the heart flashed and went dark again, and they have no idea whether it was the network or their own finger slipping. Every failure needs a visible explanation, even if it is only "It didn't work, tap to retry."
Anti-pattern four: saving optimistic state as if it were real state. Optimistic values should only live in memory, only for the current interaction. Write them to localStorage or a database, or keep treating them as real after a page refresh, and the user will see "already liked" on one refresh and "not liked" on the next. The shelf life of optimistic state is exactly one request. When the request ends, it should disappear.
Anti-pattern five: being optimistic about everything. Search results, recommendation lists, computed prices — these are results the server computes. They cannot be guessed, and they should not be guessed. Optimistic updates only belong on operations whose result you can work out in advance, and the test is the four gates above. If an operation does not pass the gates, do not force it. Waiting with a spinner is better than guessing wrong and taking it back.
Checklist: run through it before shipping
Before you start: can this operation's result be worked out in advance? Can a failure be explained in one sentence? Is it reversible and retryable? Does it touch money or irreversible deletion? Is the failure rate low enough? If any of these five questions has no answer, do not be optimistic yet.
While writing the code: use one approach per place (variables for a single spot, onMutate for several spots — never half of each in two places); mark temporary items with a pending flag so it is visible that they are not confirmed yet; write the rollback function before writing the optimistic logic; give the retry button an idempotency key; use stable ids as list keys, never indexes.
Before shipping: go offline and tap once, and check that the failure message grows next to the operation; tap "like" five times in a row and check that the final state is correct; refresh the page once and check that no optimistic state leaks through; walk the main flow on a throttled network and check for anything that "flashes and flips back." Whether optimistic updates are done well is not judged by reading the code — it is judged by these four tests: is feedback instant, is failure explained clearly, do rapid taps stay correct, and does a refresh leak nothing? Pass all four, and the experience is already a level above "wait for the server, then change."
Comments (0)
Sources
Related articles
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.
Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.
A selector is the first part of a rule: it decides who the styles land on. This guide follows MDN's Basic CSS selectors, Attribute selectors, and Pseudo-classes and pseudo-elements: type, class, ID, selector lists, universal, attribute selectors, pseudo-classes, pseudo-elements, chaining them together, plus a checklist for when a style does not show up.