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 basic useOptimistic signature: const [optimisticState, setOptimistic] = useOptimistic(state, updateFn). You should know that React 19 runs asynchronous work inside Actions. Here you will see why a <form> is the most direct way to create an Action, and how to wire an optimistic update into one.
What a form action is
In React 19 the action prop of a <form> accepts a function as well as a URL string:
<form action={handleSubmit}>
<input name="message" />
<button type="submit">Send</button>
</form>When the user submits the form, React does the following:
- It prevents the browser's default page navigation.
- It builds a
FormDataobject from the form's named fields. - It calls your function with that
FormData. - It runs the call inside a transition, so React treats it as an Action.
The function may be async. React tracks the returned Promise. The Action is pending until the Promise settles, and React finishes the transition only then.
Step 4 is what matters for optimistic updates. An optimistic value lasts for exactly one Action, and a form submission already is one.
Why the action is the right place for the setter
useOptimistic ties its temporary value to the Action that was running when you called the setter. React shows the optimistic value while that Action is pending. When the Action settles and the transition completes, React discards the optimistic value and shows the real state again.
The setter therefore has to run inside an Action or a transition. A form action gives you that for free:
| Trigger | Runs in an Action? | What you must do |
|---|---|---|
| `<form action={fn}>` | Yes, automatically | Call the setter at the top of `fn`. |
| `onClick` handler | No | Wrap the work in `startTransition(async () => { ... })`. |
| `onSubmit` handler | No | Call `event.preventDefault()` yourself and wrap in `startTransition`. |
| `useEffect`, timers, subscriptions | No | Wrap in `startTransition`, or reconsider using `useOptimistic` here. |
If you call the setter outside an Action, React warns that an optimistic update happened outside a transition or Action. The update may then not behave as you expect. The warning means the setter's context is wrong, not that the hook is broken.
The sequence of events
The order of operations in a form action is the core of this chapter.
The setter call comes before the first await. React can then render the optimistic state right away, while the network request is still in flight. If you put the setter after the await, the user waits for the server and gets no benefit from the optimistic update.
A complete example
The following runnable example has a parent that owns the real state and a child that shows the optimistic list. The deliverMessage function simulates a one-second server call.
import { startTransition, 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) {
const text = formData.get("message");
addOptimisticMessage(text);
await sendMessage(text);
}
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([{ id: "seed", text: "Hello!" }]);
async function sendMessage(text) {
const saved = await deliverMessage(text);
startTransition(() => {
setMessages((current) => [...current, saved]);
});
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}Trace what happens when the user types "Hi" and submits:
formActionreceives aFormDatawithmessage: "Hi".addOptimisticMessage("Hi")runs the update function with the current real messages and"Hi". React renders the list with a "Hi (Sending...)" row immediately.await sendMessage(text)waits about a second.- The parent's
setMessagesadds the saved message, which has a server-styleid. formActionreturns. The Action is done, so React drops the optimistic layer. The list now shows the real "Hi" without the "Sending..." label.
The startTransition around setMessages is deliberate, and the next section explains why.
Details React handles around the action
The input clears itself
For uncontrolled inputs like the one above, React resets the form after the action succeeds. You do not call form.reset() or keep the text in useState. The optimistic row appears at the moment of submission, and the empty input follows once the Action completes.
If you need the field to clear immediately, before the request finishes, you can use a controlled input. Or you can read the value, then clear your own state before the first await. In both cases the form-reset behavior does not apply to controlled fields.
State updates after an await
Inside an async Action, a plain setState call after an await is not part of the transition any more. React can render it as a normal update before the Action finishes. For a moment the real list already contains the saved message while the optimistic layer is still applied on top of it. The user would see the message twice.
Wrapping the post-await update in startTransition, as App does above, keeps it in the transition. The real state and the end of the optimistic layer then arrive together.
FormData, not events
A form action does not receive an event object. It receives FormData. Use formData.get("message") to read a field, and make sure the input has a name attribute. An input without name is not included in FormData, and get returns null. The optimistic row would then show null.
Server functions
The same pattern works when action is a Server Function marked with "use server". The optimistic setter still has to live in a Client Component, so a common structure is a small client wrapper:
"use client";
import { useOptimistic } from "react";
export function OptimisticThread({ messages, sendMessageAction }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, text) => [...current, { id: crypto.randomUUID(), text, sending: true }]
);
async function formAction(formData) {
addOptimisticMessage(formData.get("message"));
await sendMessageAction(formData);
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>{m.text}</li>
))}
</ul>
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}Here sendMessageAction is the Server Function passed in as a prop. When it finishes, the server revalidates the data, and the parent re-renders with a new messages prop. That new prop is what replaces the optimistic value.
Common errors
- Calling the setter in
onSubmitoronClickwithout a transition. React warns, and the optimistic value may flash or never show. Use a formaction, or wrap the code instartTransition. - Calling the setter after
await. The optimistic row appears only after the server answers, which defeats the purpose. Put it first. - Passing a function to
onSubmitand expectingFormData.onSubmitreceives an event. Onlyactiongives youFormData. - Forgetting
nameon inputs.formData.getreturnsnull, so the optimistic row showsnull. - Not updating the real state. If
sendMessagesucceeds but never changes themessagesprop, the optimistic row disappears when the Action ends and nothing replaces it. The message looks lost even though the server saved it.useOptimisticonly shows a guess. The real state must still be updated by you. - Mutating the current state in the update function. Return a new array, as
[...currentMessages, newItem]does. Pushing ontocurrentMessageswould change the real state.
Form action or startTransition?
Both work. Choose by the trigger:
- Use a form
actionwhen the user submits a form. You getFormData, an automatic transition, and an automatic reset. - Use
startTransition(async () => { ... })when the trigger is a click, a toggle, or a drag, where no form exists. A like button is the typical case.
Do not wrap a form in extra onSubmit logic just to use startTransition. The action prop already does that job.
Exercise
A developer writes <form onSubmit={handleSubmit}>, and handleSubmit calls event.preventDefault(), then addOptimisticMessage(text), then await sendMessage(text). React warns about an optimistic update outside a transition. What are two ways to fix it?
Show answer
One fix is to replace onSubmit with action={formAction}, where formAction(formData) calls the setter first and then awaits the request. React then runs the function inside a transition. The other fix is to keep onSubmit and wrap the body in startTransition(async () => { addOptimisticMessage(text); await sendMessage(text); }). In both cases the setter is called before the first await.
Exercise
In the complete example, a user submits "Hi" and the request succeeds, but the parent's sendMessage forgets to call setMessages. What does the user see after the Action finishes, and why?
Show answer
The "Hi (Sending...)" row appears for about a second and then disappears. The Action ended, so React discarded the optimistic layer and rendered the real messages prop, which never changed. The message may exist on the server, but the UI does not show it. The parent must update the real state (or refetch) for the saved message to appear.