Command Palette

Search for a command to run...

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

An optimistic chat with a form action

Each message appears instantly, dimmed. Hello is confirmed; please fail disappears when its Action ends and the error explains why. Try sending your own messages, including one with the word fail.

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?

An optimistic chat with a form action React 19+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

render: Welcome!
render: Welcome!, Hello (sending)
render: Welcome!, Hello
render: Welcome!, Hello, please fail (sending)
render: Welcome!, Hello