liveBook · Manning

Optimistic update

As explained in React in Depth

An optimistic update is a technique that changes locally cached data before a server mutation is confirmed, then reconciles it with the server result.

An optimistic update changes locally cached data as soon as a server mutation is sent, making the interface appear immediate while the real result is pending. The cache must later reconcile with the server response, whether that means replacing temporary data or restoring the previous state. section 9.4.2 section 9.5

Implement the mutation flow in three stages:

  • Update the local cache with the expected result when the mutation starts; imitate only the part of the server action needed for immediate feedback. section 9.4.2
  • Save the previous cache state and roll back to it if the request fails, treating failure as though the mutation never happened. section 9.4.2
  • Replace the optimistic value with the server-created data after success, because the server may assign identifiers or apply changes the client cannot predict. section 9.4.2
  • With TanStack Query, coordinate the flow through onMutate, onError, and onSuccess callbacks; cancel relevant queries before changing their cached data. section 9.4.2

Adding a goal-tracking item

When adding an item, append a temporary object such as { id: "temp", ...newData, count: 0 } to the cached list. The temporary identifier need not predict the server's random identifier; the successful response replaces the temporary item with the real object. A reusable useOptimisticMutation hook can reduce repetition when this pattern appears throughout a codebase. section 9.4.2 section 9.4.5

How React in Depth covers it

How deep it goes
Explains cache updates, snapshots, rollback, server reconciliation, and TanStack Query callbacks, but not conflict resolution.
Examples
Uses a goal-tracking list, temporary identifiers, the useAddThing hook, and the better-reactive example.
What it assumes
Assumes familiarity with remote data, local caches, mutations, and React hooks; recommends TypeScript for maintainable implementations.
What you can do after
Apply optimistic mutations with TanStack Query, including cache snapshots, rollback handling, and server-result replacement.
How it connects
Connects optimistic updates with TanStack Query, remote data, reactive caching, cache invalidation, and server mutations.

Also explained in

Compare how 2 books explain optimistic update →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.