Sub topic 9
Putting the hooks together in one form
This chapter combines useActionState, useFormStatus, and useOptimistic in a single form. It assumes you know each hook on its own, including that a function passed to <form action> runs as an Action and receives FormData.
Who owns what
Each hook has one job. Keep the jobs separate and the combined form stays simple.
| Hook | Lives in | Job |
|---|---|---|
| `useActionState` | The component that renders the form | Holds the last result (errors, values) and gives you the form action |
| `useFormStatus` | A component rendered inside the form | Reads `pending` for the parent form |
| `useOptimistic` | The component that owns the list | Shows a temporary value while the Action runs |
The data itself still belongs to a parent, a cache, or the server. useOptimistic only layers a temporary view over it.
The sequence of events
The combined form
This example is a comment box. The parent stores comments and simulates a slow save.
import { useActionState, useOptimistic, useState } from "react";
import { useFormStatus } from "react-dom";
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? "Posting..." : "Post"}
</button>
);
}
function CommentBox({ comments, saveComment }) {
const [optimisticComments, addOptimisticComment] = useOptimistic(
comments,
(current, text) => [
...current,
{ id: `pending-${current.length}`, text, sending: true },
]
);
const [state, formAction] = useActionState(
async (previousState, formData) => {
const text = String(formData.get("text") ?? "").trim();
if (text === "") {
return { error: "Write something first.", text: "" };
}
addOptimisticComment(text);
const ok = await saveComment(text);
if (!ok) {
return { error: "Could not post. Try again.", text };
}
return { error: null, text: "" };
},
{ error: null, text: "" }
);
return (
<div>
<ul>
{optimisticComments.map((comment) => (
<li key={comment.id}>
{comment.text}
{comment.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
<form action={formAction}>
<input name="text" defaultValue={state.text} />
<SubmitButton />
{state.error && <p role="alert">{state.error}</p>}
</form>
</div>
);
}
export function App() {
const [comments, setComments] = useState([]);
async function saveComment(text) {
await new Promise((resolve) => setTimeout(resolve, 800));
setComments((current) => [...current, { id: crypto.randomUUID(), text }]);
return true;
}
return <CommentBox comments={comments} saveComment={saveComment} />;
}Why it is arranged this way
- Validation runs first. An empty submission returns an error state before
addOptimisticCommentruns, so no fake comment appears and then vanishes. - The optimistic call happens inside the Action.
useActionStateruns your function in a transition.useOptimisticsetters only work inside a transition or Action. Calling one from a plain event handler triggers a warning. - Failure returns state instead of throwing. When
saveCommentreturnsfalse, the Action ends. React drops the optimistic comment, becausecommentsnever changed. The returnedtextis placed in the input throughdefaultValue, so the user's draft survives the form reset. - The button sits in its own component.
useFormStatusreads the nearest parent<form>. If you called it inCommentBox, it would find no form above it andpendingwould stayfalse. - The parent updates real data before the Action ends.
setCommentsruns beforesaveCommentreturns, so when the temporary value is discarded, the real comment is already there. If you skip this, the comment flickers out.
Common mistakes
- Calling
useFormStatusin the same component that renders<form>. - Forgetting that the optimistic value is temporary. It is not stored, so the real update must come from your data source.
- Putting
awaitbeforeaddOptimisticComment. The optimistic update should come before slow work, or the user sees no instant feedback. - Keeping duplicate pending flags.
useFormStatusand the third value fromuseActionStatereport the same thing, so use one of them.
Exercise
In the comment box, a user submits "Hello" and saveComment returns false. What does the user see, in order, and why does the draft text stay in the input?
Show answer
First "Hello" appears in the list marked "(Sending...)" and the button reads "Posting...". When the Action ends, the optimistic item disappears because comments was never updated. The error "Could not post. Try again." shows. The form resets, but the Action returned { text: "Hello" }, so defaultValue={state.text} puts "Hello" back in the input.