Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 7 · Lesson 64 · 6 min read

Optimistic Updates in React with Rollback

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: An Optimistic Todo Toggle with Rollback
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Perform server mutations with clear pending, success and error states, update the cache after a mutation by invalidation or direct writes, apply optimistic updates with rollback on failure, prevent duplicate submissions with idempotency keys, and decide when optimism is appropriate.

Concept Explanation

Reading data is half the story; users also change it: adding to a cart, renaming a file, liking a post, submitting a payment. A mutation is a request that changes server state, and it has its own lifecycle: idle, pending, success or error. The interface should reflect each: disable or mark the control while pending so users do not submit twice, confirm success where it is not obvious, and show errors next to what failed with a way to retry, without losing the user's input.

After a mutation succeeds, the cached server state is out of date. There are three ways to reconcile it. Invalidation marks related queries stale and refetches them, which is simple and always correct, at the cost of an extra request. A direct cache write uses the mutation's response, such as the updated product returned by the server, to update the cache with setQueryData, which avoids the refetch when the response contains everything needed. Combining both is common: write the returned entity into its detail entry and invalidate the lists it might appear in, since sorting and filtering may change.

An optimistic update goes further: it updates the interface immediately, before the server confirms, on the assumption that the request will succeed. Likes, checkbox toggles, reordering and renaming feel instant this way, which matters for perceived performance. The cost is handling failure correctly. The pattern is: cancel in-flight refetches for the affected queries so they do not overwrite the optimistic value, save a snapshot of the previous data, apply the optimistic change, and if the mutation fails, restore the snapshot and tell the user. After success or failure, invalidate to reconcile with the server's truth, which may differ in details such as timestamps or computed fields.

Not every mutation should be optimistic. Use optimism when success is highly likely and a rollback is easy for users to understand, such as toggles, likes and edits of the user's own content. Avoid it for actions with serious consequences or a meaningful chance of rejection: payments, bookings with limited inventory, anything requiring server-side validation the client cannot predict. For those, show a clear pending state and wait.

Duplicate submissions are a real risk: double clicks, retries after a timeout where the first request actually succeeded, or a user resubmitting after a network hiccup. Disabling the button while pending helps but is not enough. For important operations, the client generates an idempotency key once per user intent and sends it with every retry; the server stores the result for that key and returns it again instead of performing the action twice. React 19's useOptimistic and form actions provide built-in support for optimistic UI with forms, and query libraries provide onMutate, onError and onSettled callbacks for the same pattern.

StepPurposeAPI in TanStack Query
Pending statePrevent double submit, show progressisPending
Cancel refetchesStop stale data overwriting the optimistic valuecancelQueries
SnapshotAllow rollbackgetQueryData in onMutate
Optimistic writeInstant feedbacksetQueryData in onMutate
RollbackRestore on failuresetQueryData in onError
ReconcileMatch the server's truthinvalidateQueries in onSettled
Idempotency keyRetries never duplicate the actionHeader generated once per intent

Worked Example: An Optimistic Todo Toggle with Rollback

The toggle updates the list instantly, rolls back and informs the user on failure, and reconciles with the server either way. The checkout button shows the non-optimistic alternative.

TypeScript
function useToggleTodo(listId: string) {
  const qc = useQueryClient();
  const key = ['todos', listId];

  return useMutation({
    mutationFn: ({ id, done }: { id: string; done: boolean }) => api.updateTodo(id, { done }),

    onMutate: async ({ id, done }) => {
      await qc.cancelQueries({ queryKey: key });                         // no refetch may overwrite us
      const previous = qc.getQueryData<Todo[]>(key);                     // snapshot for rollback
      qc.setQueryData<Todo[]>(key, (todos = []) => todos.map((t) => (t.id === id ? { ...t, done } : t)));
      return { previous };
    },

    onError: (_err, _vars, context) => {
      if (context?.previous) qc.setQueryData(key, context.previous);     // roll back
      toast.error('Could not update the task. Your change was undone.');
    },

    onSettled: () => qc.invalidateQueries({ queryKey: key }),            // reconcile with the server
  });
}

function TodoItem({ todo, listId }: { todo: Todo; listId: string }) {
  const toggle = useToggleTodo(listId);
  return (
    <label>
      <input type="checkbox" checked={todo.done} onChange={(e) => toggle.mutate({ id: todo.id, done: e.target.checked })} />
      {todo.title}
    </label>
  );
}

// Not optimistic: payments wait for the server, and retries cannot double charge
function PayButton({ orderId }: { orderId: string }) {
  const [idempotencyKey] = useState(() => crypto.randomUUID());          // once per payment intent
  const pay = useMutation({
    mutationFn: () => api.pay(orderId, { headers: { 'Idempotency-Key': idempotencyKey } }),
    retry: 2,                                                            // safe: the server deduplicates
  });
  return (
    <button onClick={() => pay.mutate()} disabled={pay.isPending || pay.isSuccess}>
      {pay.isPending ? 'Processing payment...' : 'Pay now'}
    </button>
  );
}

Throttle the network in DevTools and toggle a task: the checkbox flips instantly. Block the request URL and toggle again: it flips, then flips back with a message, and the list refetches to confirm the server's state.

On toggle, the hook cancels in-flight refetches, snapshots the cached list and writes the new value so the checkbox flips instantly. If the server rejects the change, the snapshot is restored and the user is told. Either way, the list is refetched to match the server.
On toggle, the hook cancels in-flight refetches, snapshots the cached list and writes the new value so the checkbox flips instantly. If the server rejects the change, the snapshot is restored and the user is told. Either way, the list is refetched to match the server.

Real-World Examples

  • Stripe's API supports an Idempotency-Key header on requests that create or modify objects and returns the saved result for repeated keys, and its documentation recommends generating the key on the client so that network retries never create duplicate charges.
  • React 19 added the useOptimistic hook, which shows an optimistic state while an async action is pending and automatically reverts to the real state when the action finishes, so a failed action rolls back without manual snapshot code.
Key TakeawaysMutations have pending, success and error states that the UI must show, and they leave cached server data stale until you update it. Invalidate it, write the server's response into the cache, or both. Optimistic updates make likely-to-succeed changes feel instant: cancel refetches, snapshot, apply, roll back on error and reconcile afterward. Do not be optimistic about payments or scarce resources, and use idempotency keys for safe retries.

Review Questions & Answers

A refetch that started before the mutation could finish after the optimistic write and replace it with the old server data, making the change appear to revert. Cancelling those queries ensures only the reconciliation after the mutation updates the cache.

Cancel related in-flight queries, snapshot the current cached data, write the optimistic value into the cache, on error restore the snapshot and inform the user, and after the mutation settles invalidate the queries to reconcile with the server.

When failure is reasonably likely or consequential, such as payments, bookings with limited availability or operations with server validation the client cannot predict. Showing success and then reverting would mislead users in situations where accuracy matters most.

The client generates one key per user intent and sends it with the request and every retry. The server records the result for that key and, on seeing it again, returns the stored result instead of executing the action a second time.