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

