Hint
Optimistic updates give instant UI feedback. Always store the previous state before the optimistic update so you can revert on failure. React Query's useMutation handles this pattern automatically.
async function toggleLike(id, liked, updateUI, revertUI, saveToServer) {
// Optimistic: update UI immediately
updateUI(!liked);
try {
await saveToServer(id, !liked);
// Success: UI already correct
} catch {
// Failure: revert to original state
revertUI(liked);
}
}
let uiState = false;
let serverSaveFails = true;
const log = [];
toggleLike(
1,
false,
val => { uiState = val; log.push('ui→' + val); },
val => { uiState = val; log.push('revert→' + val); },
() => serverSaveFails ? Promise.reject() : Promise.resolve()
).then(() => console.log(log.join(' | ')));ui→true | revert→false
Explanation: UI immediately shows liked=true (optimistic). Server save fails. Revert sets UI back to liked=false. User sees instant feedback, then the rollback.
Key Insight: Optimistic updates give instant UI feedback. Always store the previous state before the optimistic update so you can revert on failure. React Query's useMutation handles this pattern automatically.