Likes that revert on failure
The first like shows 11 at once and stays (the real state caught up). The second shows 12, the server fails, and when the Action ends React drops the optimistic value: back to 11 with no undo code.
useOptimistic(state, update?) shows a temporary, hoped-for version of some state while an Action runs; when the Action ends React drops the temporary value and shows the real state again, so a failed request reverts by itself.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Make a to-do checkbox that toggles optimistically and reverts if fakeToggle() rejects.
Add optimistic "(sending)" items to a comment form backed by useActionState.
Explain it without notes
What is optimistic UI, and when is it a good idea?
How does useOptimistic revert a failed update?
Why must addOptimistic be called inside an Action?
How do you combine useOptimistic with a form action correctly?
Preview
Console
Nothing logged yet.Expected console output
render likes=10 shown=10
render likes=10 shown=11
render likes=11 shown=11
render likes=11 shown=12
failed, reverting
render likes=11 shown=11