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.
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: Welcome!
render: Welcome!, Hello (sending)
render: Welcome!, Hello
render: Welcome!, Hello, please fail (sending)
render: Welcome!, Hello