Optimistic UI shows a mutation's result before the server confirms it, so every optimistic write owes three things: a snapshot taken before the change, a rollback to that exact snapshot on any failure, and a reconcile against true server state on settle. The bugs are never in the happy path — they surface as un-rolled-back fakes, duplicated rows, temp ids that outlive the response, and flicker when a refetch races the mutation.
Checklist (lead with the trap)
- Snapshot before you apply — and roll back to the snapshot, not by inverting the delta. Capture the prior value (
getQueryData, the prior list, prior form state) before the optimistic write and restore it on failure. Rolling back by re-subtracting/undoing the delta double-counts once a second mutation has touched the same value; restore the captured snapshot instead. - Cancel in-flight refetches before the optimistic write. In TanStack Query,
await cancelQueries({ queryKey })insideonMutate; otherwise a refetch already running resolves after your optimistic write and silently clobbers it (the docs call this out inline). - Wire rollback to every failure exit.
onErrorrestores the snapshot; amutationFn/promise that rejects (or throws before the request even leaves) with no rollback leaves the fake state permanently. SWR rolls back by default (rollbackOnError: true, and it accepts a per-error function), so confirm any error types you exempt (e.g.AbortError) are exempted on purpose. - Reconcile with server truth on settle — don't trust the optimistic value. Invalidate/refetch in
onSettledso server-derived fields (ids, timestamps, normalized or partially-rejected values) replace the guess. Return the invalidation promise if the mutation should stay pending until the refetch resolves. - Swap the temp client id for the server id — don't leave both. An optimistic insert uses a temp id (a uuid or
temp-prefix); when the response arrives, replace that entry, don't append the real one beside it, or a refetch shows the row twice. In Apollo, include__typename+ id so the normalized cache can merge temp to real, and use anupdatefn to place new objects into list queries. A later edit/delete still pointing at the temp id hits nothing. - Don't both write the result and invalidate the same query un-guarded. Writing the server result in
onSuccessand invalidating fires a redundant refetch that can flicker; pick one reconcile path per query (write-through, or invalidate-and-refetch). - Order concurrent mutations to the same resource. Mutations run in parallel by default; two writes to one record race and last-response-wins can corrupt state. Give related mutations a
scope: { id }(TanStack) so same-scope mutations run serially, or debounce/queue at the call site. - Know the concurrent-refetch window. If a second mutation starts while the first is still in flight there is nothing for it to cancel; when the first mutation's invalidation refetch resolves faster than the second mutation settles, the UI reverts (the "window of inconsistency"). Mitigate with query cancellation plus fine-grained invalidation — tag related mutations with a
mutationKeyand gate onisMutating. useOptimistic: pure reducer off the current base, and something must persist. The reducer must recompute from its current-state argument, not a captured stale list — React re-runs it if the base changes mid-transition (e.g. another client's insert lands). The value auto-reverts when the action/transition completes, so if no real mutation runs inside that transition it simply snaps back.
Quick probes
Treat hits as leads; confirm the snapshot to apply to rollback to reconcile path at the call site.
rg -n 'onMutate|cancelQueries|getQueryData|setQueryData|invalidateQueries|onSettled' src/ app/ 2>/dev/null
rg -n 'optimisticData|rollbackOnError|populateCache|useOptimistic|optimisticResponse' src/ app/ 2>/dev/null
rg -n 'temp-|tmpId|tempId|nanoid\(|crypto\.randomUUID' src/ app/ 2>/dev/null # temp-id creation -> is it ever swapped?
rg -n 'scope:\s*\{|mutationKey|isMutating' src/ app/ 2>/dev/null # concurrency ordering
Boundary with sibling skills
- This skill: the optimistic-apply / rollback / reconcile lifecycle — snapshot, cancel, apply, roll back on failure, temp-to-server id swap, refetch reconcile, and ordering of concurrent optimistic writes.
- js-form-validation-contracts — submit-in-flight, double-submit, and async/server-error races inside a form (a create mutation is often both; keep the form's submit-gating there and the cache rollback here).
- a11y-contract-testing — announcing success, failure, and rollback to assistive tech (a live region /
role="alert"for a silent revert). - ssr-hydration-mismatch — server vs client initial render divergence (an optimistic value seeded at hydration is a different bug from one applied on user action).
- frontend-data-fetching-cache-contracts — whether the settle-time invalidation targets the key/tag the reader actually subscribes to, plus key design and serialization (exact
invalidateQueriesfilters, ApollokeyFields/typePolicies, SWR key scoping). The invalidate-after-mutation call is the seam: it fires here, and its target key belongs there. - realtime-transport-contracts — pushed deltas (WebSocket/SSE) written into the same cache: sequence-based dedupe, ordering, gap detection, and replay after reconnect. This skill owns only how an optimistic entry reconciles once the confirming delta lands.
PR-worthiness gate
File a finding only when a user-visible reconciliation contract is broken:
- No rollback: an optimistic write with no snapshot, or the
onError/rollbackOnErrorpath missing, so a failed request leaves fake state. - Un-swapped temp id: create shows the row twice after refetch, or a follow-up edit/delete targets a temp id the server never knew.
- Clobber / flicker: missing
cancelQueriesbefore an optimistic write, or anonSuccesscache-write plus invalidation both firing, producing a visible revert-then-reappear. - Ordering: concurrent mutations to the same record with no serialization/queue where order actually matters.
Reject weak findings:
- A mutation that already has snapshot + rollback +
onSettledinvalidate — that is the correct pattern, not a defect. - Optimistic UI on a low-failure single-surface action using
useOptimistic/variables with no cache rollback — intentionally simpler; don't demand the full cache dance. - Pure "which
queryKeyto invalidate" tuning with no rollback, temp-id, or ordering defect — route it to frontend-data-fetching-cache-contracts rather than filing it here. - A non-optimistic mutation (spinner until confirmed) — out of scope.
Minimal useful PR: one failing test that drives apply -> server-error -> assert rollback to the snapshot; plus, for creates, apply temp id -> server response -> assert a single row under the real id and no duplicate after refetch.
Output shape
- Contract: snapshot/rollback | temp-to-server id swap | refetch reconcile | concurrency ordering.
- Evidence: file/line and the mutation's
onMutate/onError/onSettled(oroptimisticData/useOptimistic) path. - Symptom: un-rolled-back fake, duplicate row, flicker/revert, orphaned temp id, out-of-order write.
- Fix: smallest change — add snapshot+rollback, add
cancelQueries, temp-id swap,scope.id, or the missing invalidate. - Verification: unit/integration test asserting rollback and post-settle single-source state.
Sources
- TanStack Query — Optimistic Updates (cache approach:
cancelQueries-> snapshot ->setQueryData-> roll back inonError-> invalidate inonSettled; return the invalidation promise): https://tanstack.com/query/v5/docs/framework/react/guides/optimistic-updates - TanStack Query — Mutations /
useMutation(scope: { id }runs same-scope mutations serially; otherwise parallel): https://tanstack.com/query/latest/docs/framework/react/guides/mutations - TkDodo — Concurrent Optimistic Updates in React Query (query cancellation, the "window of inconsistency",
mutationKey+isMutating): https://tkdodo.eu/blog/concurrent-optimistic-updates-in-react-query - TkDodo — Mastering Mutations in React Query (when optimistic is overkill; returning the invalidation promise to hold the pending state): https://tkdodo.eu/blog/mastering-mutations-in-react-query
- SWR — Mutation & Revalidation (
optimisticData,rollbackOnError,populateCache,revalidate): https://swr.vercel.app/docs/mutation - React —
useOptimistic(auto-revert when the action completes; pure reducer recomputed from the current base state): https://react.dev/reference/react/useOptimistic - Apollo Client — Optimistic mutation results (
optimisticResponsewith__typename+ temp id;updatefn to add to lists; temp-to-canonical cache-id swap): https://www.apollographql.com/docs/react/performance/optimistic-ui - Apollo Client — Caching overview (normalized cache id =
__typename:id, which makes the temp-to-real merge possible): https://www.apollographql.com/docs/react/caching/overview