Sub topic 6
Form actions as the natural place to update optimistically
This chapter assumes you know useState, props, and async/await. It also assumes you have seen the useOptimistic signature, which takes real state and returns optimistic state plus a setter. Here you will see why a form action is the easiest place to call that setter.
Why form actions fit
The setter returned by useOptimistic only works inside an Action. An Action is an async function that React runs inside a transition. Without that context, React warns you, and the optimistic value does not behave as intended.
In React 19, a function passed to a form's action prop is already an Action. React calls it with a FormData object and wraps the call in a transition, so you don't need to write startTransition yourself. The submit handler is therefore a safe place for the optimistic update.
The pattern inside the action has three steps:
- Read the values you need from
FormData. - Call the optimistic setter right away.
- Await the server call.
The setter call is synchronous, so the screen updates before the request finishes. While the Action is pending, React shows the optimistic value. When the Action ends, React shows the real state again.
The full flow
A complete example
The parent owns the real messages state. Its sendMessage function waits for the server, then updates that state. The child component runs the optimistic update.
import { useOptimistic, useState } from "react";
async function deliverMessage(text) {
await new Promise((resolve) => setTimeout(resolve, 1000));
return { id: crypto.randomUUID(), text };
}
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, text) => [
...currentMessages,
{ id: crypto.randomUUID(), text, sending: true },
]
);
async function formAction(formData) {
addOptimisticMessage(formData.get("message"));
await sendMessage(formData);
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>
{m.text}
{m.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}
export default function App() {
const [messages, setMessages] = useState([]);
async function sendMessage(formData) {
const saved = await deliverMessage(formData.get("message"));
setMessages((current) => [...current, saved]);
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}Submit "hello" and the message appears at once with "(Sending...)". One second later setMessages runs. When formAction finishes, React drops the optimistic list and renders messages, which now holds the saved message.
Details that matter
- Order of calls. Call the optimistic setter before the first
await. Updates made after anawaitinside a transition can lose their Action context, depending on the React version and how you wrote the code. - Real state must change before the Action ends. The optimistic value disappears when the Action finishes. If the parent has not updated
messagesby then, the new message flickers away. - The form resets itself. After a function action completes, React clears uncontrolled fields, so you don't need to reset the input by hand.
- Not only forms. A button that triggers an async handler needs
startTransition, as in the like-button example you saw earlier. A form action gives you that wrapper for free.
Common errors
| Symptom | Likely cause |
|---|---|
| Console warning about an optimistic update outside a transition | Setter called from a plain event handler without `startTransition` |
| Message appears, then vanishes, then reappears | Parent updates real state after the Action has already ended |
| Message never appears until the server replies | Setter called after the `await` instead of before it |
Exercise
In the example, formAction is passed to <form action>. Why is it safe to call addOptimisticMessage there without wrapping it in startTransition?
Show answer
React runs a function passed to a form's action prop as an Action inside a transition. The optimistic setter is therefore already called in the context it needs.
Exercise
A learner's message shows "(Sending...)", then disappears for a moment, then comes back as a normal message. What is the likely bug, and how do you fix it?
Show answer
The parent updates its real messages state after the form action has already finished. Make the action wait until setMessages has run, for example by awaiting the server call and updating state inside the awaited sendMessage function.