Skip to content

Optimistic updates and rollback

Show the result of an action before the server confirms it, keep a way back, and if the server says no, undo the guess and show what the server has. A strong answer names each step on screen.

On this page

What it is

An optimistic update draws the outcome of an action the moment the person asks for it, and sends the request afterwards. The older pattern disabled the button, waited for the server, then redrew the page from its answer. The optimistic pattern skips the disabled state and shows success right away, on the assumption that user-initiated requests succeed the great majority of the time; the Smashing Magazine piece on the pattern argues that with a stable API the refusal rate should stay around 1 to 3 percent. The payoff is perceived speed: feedback within about 0.1 seconds reads as instantaneous, and anything slower turns a tap into a wait.

Three pieces make it work. The guess is the value you render before the server answers: a toggled flag, a count plus one, a new row with the text the person typed. The way back is whatever lets you undo the guess if the server refuses. The reconciliation is what happens when the real answer arrives: it replaces the guess, whether or not it matches. React's useOptimistic hook is built around this shape. It takes the confirmed value and returns a temporary one while an Action is pending; when the Action finishes, the confirmed value shows again, in the same render, with no separate step to clear the guess. If the Action throws, the Transition still ends, and because the parent usually updates the confirmed value on success and not on failure, the screen goes back to what it showed before the tap. You catch the error to tell the person what happened.

There are two common ways to keep a way back. Snapshot and restore: before writing the guess into your client cache, copy the current value, write the guess, and if the request fails write the copy back. In TanStack Query v5 this is the onMutate handler returning the previous data, onError writing it back, and onSettled invalidating the query so a refetch fetches the truth either way. Render from pending input: don't touch the cache at all. The mutation exposes isPending and the variables it was called with, so the list renders a faded extra row from those variables while the request is pending. When it settles, the row stops rendering on its own, and a successful refetch shows the real one. Nothing has to be rolled back. On error the variables are kept, so you can keep showing the row in an error style with a retry button.

Creating something new adds a wrinkle: the client has no id for it yet. Apollo Client v4 handles this by asking for a temporary id in the optimisticResponse; the cache stores the guess under that temporary identity, and when the server responds the optimistic object is removed and the real one is cached under its real id. Apollo also keeps the guess in a separate optimistic layer rather than overwriting the cached object, so a wrong guess doesn't corrupt the confirmed data, and a GraphQL error discards the layer to return to the previous state.

ts
// Snapshot-and-restore, written without a library.
// The server's contract here: a refusal is a JSON body { applied: false, reason }.
async function follow(userId: string) {
  const before = store.get(userId);               // the way back
  store.set(userId, {
    ...before,
    following: true,
    followers: before.followers + 1,              // the guess
    pending: true,
  });
  let res: Response;
  try {
    res = await fetch(`/users/${userId}/follow`, { method: 'POST' });
  } catch {
    // fetch threw (for example a dropped connection): treat the outcome as unknown.
    await refetchUser(userId);                     // ask the server, don't assume
    return;
  }
  if (res.ok) {
    const fresh = await res.json();
    store.set(userId, { ...fresh, pending: false }); // reconciliation: server value wins
    return;
  }
  const body = await res.json().catch(() => null);
  if (body?.applied === false) {
    // The server says it did not apply the change, so restore the snapshot taken before the guess.
    store.set(userId, before);                     // restore
    toast(body.reason ?? 'Could not follow.', () => follow(userId));
    return;
  }
  // Any other failure: we don't know what the server did, so ask it.
  await refetchUser(userId);
}

When to use it

Use it for actions that are cheap, reversible and that the server has little reason to refuse: liking, following, toggling a setting, marking something read, adding a comment, reordering a list. Before choosing it, check the real refusal rate for that endpoint; the pattern's own premise is that refusals are rare, so an endpoint that often says no is a poor fit however small the action looks. Like buttons are the example most people have seen: the Smashing Magazine piece shows Twitter's button switching to its active state on the tap, while the request is still in flight.

Pick the way back by how many places show the result. When one component shows it, rendering from the pending variables is less code and needs no rollback logic. When several views would need to know (a feed card, a profile header, a notification count), writing the guess into the shared cache updates all of them at once, and that's when snapshot-and-restore earns its complexity.

Design the failure as carefully as the success. The argument for speed is that the person stays in the flow of what they're doing; the same argument says a refusal should reach them while they're still in that flow, which the Smashing Magazine piece puts at about 2 seconds after the action. Restore the old value, say what happened in plain words near the thing that changed, and keep the input so a retry costs one tap rather than retyping. A rejection that arrives silently, or after they've scrolled away, can leave the screen wrong until the data is next refreshed.

Guard against the race with reads. If a background refetch of the same data is in flight when you write the guess, its answer can land afterwards and overwrite the guess with pre-action data, so the person sees their like vanish and then reappear. TanStack Query's recipe cancels outgoing refetches for that key before writing the guess. React's useOptimistic takes the other route: when you pass a reducer and the confirmed value changes while the Action is pending, the reducer runs again on the new value, so the guess sits on top of the fresh data instead of being lost.

When not to

Don't guess when being wrong costs more than the wait saves. Payments, sending a message that others see at once, deleting something without an undo, and anything the person can't take back deserve a pending state and a confirmed result. Don't guess when the server computes the answer: a search, a price, a validation that depends on data you don't have. And don't guess when refusals are routine, such as an action that hits permission checks or rate limits often; the whole pattern rests on refusals being rare, and a screen that flips back several times a session teaches people to distrust it.

A timeout or a dropped connection is not a refusal. The server may have applied the change and the acknowledgment got lost. Rolling back in that case shows the person a state that may be false in the other direction. Our advice: on an unknown outcome, refetch and show whatever the server has, and make the request safe to repeat so a retry doesn't double-apply (Idempotency keys). TanStack Query's guide reaches a similar place: in most failure cases, refetching the affected queries is enough to return them to the server's state, and an explicit rollback is for the cases where a refetch won't work.

Be careful with a brand-new object before the server has named it. Until the real id comes back, the row exists under a temporary id the server doesn't know, so a follow-up action on it (delete it, reply to it) has nothing valid to send. Our advice: disable follow-up actions on a pending row, or queue them until the real id arrives. Give the rendered row a stable client-side key that doesn't change when the real id arrives, because a key that flips from temporary to real can make the row remount, which reads as a jump and can drop focus.

Compared

ApproachHow it worksReach for it whenWhat it costs

Pessimistic (wait, then show)

Disable the control, send, redraw from the response

The action is irreversible, involves money, or the server computes the result

A visible wait on each action

Optimistic, rendered from pending input

Show a temporary row from the mutation's variables while it's pending; it disappears when the request settles

One component shows the result

Other views may not see the change until the refetch

Optimistic, snapshot and restore

Copy the cached value, write the guess, restore the copy on error, refetch on settle

Several views share the data

Rollback code, and a stale snapshot can wipe a second overlapping update

Optimistic, refetch on failure

Write the guess, and on any failure refetch the truth instead of restoring

The outcome may be unknown (timeouts), or you can't be sure the snapshot is still right

An extra request, and a longer moment showing the wrong value

Layered optimistic cache

Keep the guess in a separate layer over the confirmed object; the response replaces it, an error drops it

A normalized cache with stable ids

Needs a stable identifier for each object, including a temporary one for new ones

In a picture

Tap FollowFollowing, 1201Keep old recordPOST follow

Step 1 of 3

The tap draws the guess

The person taps Follow. The screen flips to Following and the count goes from 1,200 to 1,201 at once, from a value the client computed. The previous record is kept. Then the request goes out.

How to say it in an interview

The common mistake

Quiz

An optimistic follow request times out with no response. What should the client do?
Two optimistic edits to the same list overlap. Each took a snapshot before writing. The first fails and restores its snapshot. What happens to the second edit?
A comment is added optimistically with a temporary id. Before the server responds, the person taps delete on it. What is the problem?
With React's useOptimistic, the Action awaiting the save throws. What does the component render next?

Questions that use this

Hear it in

Related

Sources

  1. React reference: useOptimistic (React 19.3)
  2. TanStack Query v5 guide: Optimistic Updates
  3. Apollo Client v4 docs: Optimistic mutation results
  4. Nielsen Norman Group: Response Times: The 3 Important Limits
  5. Smashing Magazine: True Lies Of Optimistic User Interfaces
Sign in to report a mistake