Advanced React Interview QuestionsAdvancedConcept
React · Question 82
How does useOptimistic work, and what happens when an Action fails?
Direct answer
useOptimistic temporarily renders an expected state while an Action is pending; when the Action finishes the UI converges to the real value, and if the mutation fails the optimistic state disappears unless the canonical value was changed.
LikeButton.jsx
function LikeButton({ liked, saveLike }) {
const [optimisticLiked, setOptimisticLiked] =
useOptimistic(liked);
function handleClick() {
startTransition(async () => {
setOptimisticLiked(true);
await saveLike();
});
}
return (
<button onClick={handleClick}>
{optimisticLiked ? "Liked" : "Like"}
</button>
);
}- Immediate feedback: optimistic state can appear before the server confirms the mutation.
- Canonical value: the normal value remains the source that determines what survives after the Action.
- Failure: if the Action fails and the canonical value never updates, React returns to that canonical value after the Action ends.