Optimistic Updates with RTK Query
You'll learn how to make your UI feel instant by updating the cache before the server confirms the change.
What Are Optimistic Updates?
Optimistic updates let you assume a mutation will succeed and immediately update the UI, rather than waiting for the server response. If the mutation fails, you roll back the change. This creates a snappy, responsive feel—think of liking a post on social media: the heart fills instantly, even though the request is still in flight.
How RTK Query Implements Optimism
With RTK Query, you manually patch the cache inside your mutation's onQueryStarted lifecycle. You apply the change immediately, then await the server response. If it succeeds, the cache stays updated. If it fails, you use the undo function to revert.
The pattern looks like this:
// In your API slice
addPost: build.mutation({
query: (post) => ({
url: '/posts',
method: 'POST',
body: post,
}),
async onQueryStarted(post, { dispatch, queryFulfilled }) {
// Optimistically add the post to the cache
const patchResult = dispatch(
api.util.updateQueryData('getPosts', undefined, (draft) => {
draft.push({ ...post, id: 'temp-id' });
})
);
try {
await queryFulfilled; // Wait for server confirmation
} catch {
patchResult.undo(); // Roll back on failure
}
},
}),
You're manually using updateQueryData to patch the getPosts cache, adding the new post immediately. The server might take 500ms to respond, but your user sees the update in 0ms.
Key Takeaway: Optimistic updates with RTK Query require manually patching the cache in onQueryStarted, then rolling back with undo() if the mutation fails—giving users instant feedback while maintaining correctness.