State Management · Senior · Question 21 of 75
How do you implement an optimistic update with the cache in TanStack Query?
- ✓Correct answer:
onMutate: cancel queries, snapshot and update the cache;onError: roll back;onSettled: invalidate - 2Call
invalidateQueriesat the start of the mutation - 3Set
optimistic: trueon the list query
Explanation
cancelQueries prevents an in-flight refetch from overwriting the optimistic data; the snapshot from getQueryData is returned as context for rollback. v5 also has a simpler approach: render variables while the mutation isPending, without touching the cache.