Prompt
Implement optimistic updates with React Query for a "like" toggle on a post. Update the cache immediately, then revert on API failure.
Solution
Optimistic updates buy perceived latency: on a mobile network a like round-trip can take a second, and a button that doesn't respond for a second reads as broken. The pattern assumes success, updates the cache immediately, and treats failure as the exceptional path to roll back.
The choreography is a three-beat contract, and each beat exists for a specific race:
onMutate: cancel, snapshot, write.cancelQueriesfirst — if a background refetch for this key is already in flight, its response would land after your optimistic write and overwrite it with pre-mutation data. Then snapshotpreviousand write the optimistic value.onError: restore the snapshot. Thecontextreturned fromonMutatecarriespreviousto the error handler — that return value is the designed hand-off, not a convenience.onSettled: invalidate. Success or failure, refetch the key so the cache converges on the server's truth — your optimistic guess and the server's result (like counts, timestamps) can differ even on success.
Red flag: skipping cancelQueries. The demo works, then in production a refetch races the optimistic write and users watch their like flicker off. Knowing why the cancel is there is the senior tell.
Say it: "Optimistic UI is cancel, snapshot, write, then roll back on error via the onMutate context — and always invalidate on settle so the cache reconverges with the server."