Back to all posts
·8 min read

Optimistic updates in React: a fast UI with consistent server state

When you tick a checkbox in a task list and the checkmark appears without waiting for the server, the interface feels noticeably faster. That is what we call an optimistic update: we assume the operation will most likely succeed, show the result immediately, and reconcile the state with the server's answer once it arrives.

The idea is simple, but the implementation easily gets messy. On failure, wrong data stays on the screen; two operations fired back to back overwrite each other; the temporary ID of a newly created record does not match the ID that comes back from the server. In this post I describe the model I use to make optimistic updates predictable in React, and the points I pay attention to. The examples are not tied to a particular data-fetching library; the same ideas can be adapted to whatever caching layer you use.

When an optimistic update is the right choice

Not every operation is a good fit for optimistic display. Good candidates are operations with a high chance of success, whose rollback would not confuse the user, and whose outcome can largely be predicted on the client: liking an item, marking a task as done, reordering a list, adding a short comment.

By contrast, being optimistic about irreversible operations, or operations whose outcome depends tightly on server-side rules, misleads the user: taking a payment, confirming an order, permanently deleting something, or sending notifications to other people. Showing "Your payment was received" and taking it back a few seconds later is a much worse experience than waiting. For these operations, an explicit loading state and the server's definitive answer are more honest.

The question I ask myself is: "If this operation fails and I roll back the change on screen, will the user understand what happened?" If the answer is yes, an optimistic update is a good choice.

Separating confirmed state from pending changes

The most common mistake I see is writing the optimistic change directly over the data that came from the server. Once you do that, you lose track of which fields are confirmed and which are guesses, and it becomes unclear what to return to when something fails.

A sturdier model keeps two separate things: the last state the server confirmed, and the list of operations that have not settled yet. The data shown on screen is derived by applying the pending operations, in order, on top of the confirmed state.

type Todo = { id: string; title: string; done: boolean };

type PendingOp =
  | { opId: string; kind: "toggle"; id: string; done: boolean }
  | { opId: string; kind: "add"; todo: Todo };

function applyOp(list: Todo[], op: PendingOp): Todo[] {
  switch (op.kind) {
    case "toggle":
      return list.map((t) => (t.id === op.id ? { ...t, done: op.done } : t));
    case "add":
      return [...list, op.todo];
  }
}

function visibleTodos(confirmed: Todo[], pending: PendingOp[]): Todo[] {
  return pending.reduce(applyOp, confirmed);
}

The benefit of this structure is that when an operation succeeds, you remove it from the pending list and write the data returned by the server into the confirmed state. When it fails, you only remove the operation from the list; the visible data returns to the correct shape on its own. There is no need for a separate "save the previous state and restore it" step.

Temporary IDs and matching them to server IDs

When adding a new record, the ID the server is supposed to assign does not exist yet. You need to generate a temporary ID on the client (for example with crypto.randomUUID()) and display the record with it. The trouble starts when the server returns the real ID: components that use the temporary ID as a key get recreated, focus is lost, and any other pending operation on that record targets the wrong ID.

There are two practical solutions. The first is to generate the ID on the client where possible, send it to the server, and have the server accept it. In systems that use UUIDs this is usually the cleanest path, and the same ID also acts as an idempotency key when a request is resent. The second is to keep a mapping between client and server IDs and replace the temporary ID with the real one when sending pending operations. The second approach needs more code; if you can leave ID generation to the client, prefer the first.

Rolling back on failure

When an operation fails, removing the pending operation is not the only thing to do; you also need to tell the user in an understandable way. A checkmark that silently disappears makes the user think "I clicked, but I guess it didn't work" and repeat the action.

async function toggleTodo(id: string, done: boolean) {
  const op: PendingOp = { opId: crypto.randomUUID(), kind: "toggle", id, done };
  dispatch({ type: "pending/added", op });

  try {
    const saved = await api.updateTodo(id, { done });
    dispatch({ type: "op/confirmed", opId: op.opId, todo: saved });
  } catch (error) {
    dispatch({ type: "op/failed", opId: op.opId });
    notify.error("The task could not be updated. Please try again.");
  }
}

Reacting according to the type of error matters as well. For transient problems such as network errors, it can make sense to retry the operation once automatically. For permanent problems such as validation or authorization errors, retrying is pointless; you need to roll back the change and show the reason. For a concurrency conflict (for example when the server returns 409 or 412), the safest path is to fetch the current data again and show the user the latest state.

Ordering and race conditions

If the user clicks the same checkbox twice in quick succession, two requests go out. The responses can come back over the network in a different order; if the response to the earlier request arrives last, the confirmed state reverts to the old value. This is one of the hardest bugs to notice in optimistic interfaces, because it only shows up on slow or unstable connections.

There are a few ways to handle it:

  • Queue operations that target the same resource: Allow only one request in flight per record, and make later ones wait for the previous one to finish. Simple and predictable.
  • Ignore stale responses: Keep the ID of the latest operation for each record; if a returning response does not belong to the latest operation, do not write it into the confirmed state.
  • Use versions on the server side: If the record has a version field or an ETag, the client sends it and the server rejects updates based on an outdated version. Besides the client's own races, this also catches conflicts with other users.

The pending operations list helps here too. Because the list is ordered, when the confirmed state is updated, the operations that are still pending are reapplied on top of it, and the user's latest intent stays on screen.

Honest feedback to the user

An optimistic interface does not have to claim "done". Showing a pending change slightly differently, for example in a fainter colour or with a small syncing indicator, feels fast and stays honest at the same time. Especially in mobile settings with slow connections, this tells the user what has actually been committed.

It is also useful to know whether there are pending operations when the user tries to leave the page. For non-critical operations a warning may be overkill, but for form-like, data-heavy input, an "unsaved changes" warning prevents data loss.

On the accessibility side, error notifications need to reach screen readers too. Placing the notification component inside an appropriate live region (aria-live) ensures that a rolled-back change is announced audibly, not only visually.

Testing optimistic behaviour

What really needs testing in optimistic updates is not the happy path but the failure and ordering scenarios. Writing the state logic as pure functions (applyOp, visibleTodos, and the reducer) makes it easy to test them independently of components.

test("a failed operation is removed from the visible data", () => {
  const confirmed = [{ id: "1", title: "Write", done: false }];
  let state = reducer(initial(confirmed), {
    type: "pending/added",
    op: { opId: "a", kind: "toggle", id: "1", done: true },
  });
  expect(visibleTodos(state.confirmed, state.pending)[0].done).toBe(true);

  state = reducer(state, { type: "op/failed", opId: "a" });
  expect(visibleTodos(state.confirmed, state.pending)[0].done).toBe(false);
});

At the component level, replacing the API call with a controllable fake and delaying or reordering its responses lets you reproduce race conditions reliably. Tests that rely on the real network being slow are flaky; the test itself should decide when a response comes back.

Conclusion

Optimistic updates are one of the most effective ways to make an interface feel fast, but they should be treated not as a trick but as a state model with consistency rules. Separating confirmed state from pending operations, thinking about IDs up front, handling errors by type, managing ordering deliberately, and honestly showing the user what has been committed are the core parts of that model. Once these parts are in place, you no longer have to choose between speed and correctness.