Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 19.6 — useOptimistic
React · Example 1 of 2 React 19+

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.

01

Make a to-do checkbox that toggles optimistically and reverts if fakeToggle() rejects.

02

Add optimistic "(sending)" items to a comment form backed by useActionState.

Explain it without notes

01

What is optimistic UI, and when is it a good idea?

02

How does useOptimistic revert a failed update?

03

Why must addOptimistic be called inside an Action?

04

How do you combine useOptimistic with a form action correctly?

Likes that revert on failure React 19+

Preview

Press Run to see the page.

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