How do you implement optimistic updates with Redux Toolkit?

Answer

Optimistic updates immediately update the UI before the server confirms, creating a responsive feel. With RTK Query: updatePost: builder.mutation({ query: ({ id, ...patch }) => ({ url: \`/posts/\${id}\`, method: "PATCH", body: patch }), async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) { const patchResult = dispatch(api.util.updateQueryData("getPost", id, (draft) => { Object.assign(draft, patch); })); try { await queryFulfilled; } catch { patchResult.undo(); } } }). How it works: updateQueryData optimistically updates the cache. If the request fails, patchResult.undo() reverts the cache. With regular thunks: dispatch the optimistic action first, then the async action. On success, the real data replaces the optimistic data. On failure, dispatch a rollback action. Key consideration: always handle errors and revert — unreverted optimistic updates on failure create data inconsistencies. Show error notifications when rollback occurs so users know their action failed.