HardAsync in React💻 Output Question

Optimistic update — immediate UI, rollback on failure

💡

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.

What does this output?

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(' | ')));

Correct Output

ui→true | revert→false

Why this output?

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.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz