Lesson 7 of 30
The decision to use an optimistic update is a judgment call; actually implementing one correctly is a specific, repeatable code shape — and most of the bugs live in the rollback path, not the happy path.
13 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 3
In an optimistic update implementation, when should the previous value be captured for rollback purposes?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
Implementing an optimistic update correctly means writing four steps, in this order, every time:
function useOptimisticMutation<T>(
current: T,
setCurrent: (value: T) => void,
) {
const [pending, setPending] = useState(false);
async function run(optimisticValue: T, mutate: () => Promise<T>) {
const previous = current; // 1. capture
setCurrent(optimisticValue); // 2. apply immediately
setPending(true);
try {
const confirmed = await mutate(); // 3. fire the real request
setCurrent(confirmed); // 4a. success — reconcile with server truth
} catch (err) {
setCurrent(previous); // 4b. failure — roll back
showErrorToast("Couldn't save your change. Please try again.");
} finally {
setPending(false);
}
}
return { run, pending };
}
// usage: liking a post
const { run } = useOptimisticMutation(post.likeCount, setLikeCount);
function handleLike() {
run(post.likeCount + 1, () => api.likePost(post.id));
}
The failure branch is doing the actual work this lesson is about. Skipping it — catching the error only to log it, with no rollback and no user-facing signal — is what turns a nice-feeling feature into a UI that lies about what happened.
pending/in-flight state still matters even though the UI already looks updated. A double-submit guard (disabling the button while pending) is still needed — the UI looking done doesn't mean the request is done."Show me how you'd actually implement the rollback if this fails" is the natural follow-up once optimistic updates come up, and the strong answer is the capture-apply-confirm-or-rollback shape above, with the second-in-flight-update edge case named unprompted.