Sub topic 9
Putting the hooks together in one form
This chapter assumes you already know useTransition, useActionState, useFormStatus, and useOptimistic one at a time. It also assumes you are comfortable with FormData and async functions. Here you combine them in a single form and learn which hook owns which job, what order things happen in, and where the combinations go wrong.
Who owns what
Each hook answers a different question. Problems start when two hooks are asked the same question or when none answers one.
| Question | Hook | Where it can be called |
|---|---|---|
| Is the Action running right now? | `useActionState` (third value) or `useFormStatus` | `useActionState` in the component that owns the Action. `useFormStatus` only in a component rendered inside the `<form>`. |
| What did the last Action return? | `useActionState` (first value) | The component that owns the Action |
| What should the user see before the server answers? | `useOptimistic` | The component that holds the real data |
| Which values were submitted? | `FormData` | Inside the Action |
A useful rule is that useActionState owns the form's result, useOptimistic owns a temporary view of the data, and useFormStatus is only a way for child components to read "pending" without prop drilling.
The scenario
You will build a small to-do list with these requirements:
- The new item appears in the list immediately, marked "(saving...)".
- If the server rejects it, the item disappears and an error message appears.
- Empty titles are rejected before any request is made.
- The submit button is a separate component that disables itself while saving.
- After a success the input clears. After a failure it keeps what the user typed.
The server is simulated with a function that waits and then fails when the title contains the word "fail". This lets you test both paths without a backend.
The complete component
import { startTransition, useActionState, useOptimistic, useState } from "react";
import { useFormStatus } from "react-dom";
async function saveTodo(title) {
await new Promise((resolve) => setTimeout(resolve, 800));
if (title.toLowerCase().includes("fail")) {
throw new Error("The server rejected this item.");
}
return { id: crypto.randomUUID(), title };
}
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? "Adding..." : "Add"}
</button>
);
}
export function TodoApp() {
const [todos, setTodos] = useState([]);
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
(current, title) => [
...current,
{ id: `pending-${current.length}`, title, sending: true },
]
);
async function addTodo(previousState, formData) {
const title = String(formData.get("title") ?? "").trim();
if (title === "") {
return { error: "Title is required.", title: "" };
}
if (title.length > 100) {
return { error: "Title must be 100 characters or fewer.", title };
}
addOptimisticTodo(title);
try {
const saved = await saveTodo(title);
startTransition(() => {
setTodos((current) => [...current, saved]);
});
return { error: null, title: "" };
} catch (err) {
return { error: err.message, title };
}
}
const [state, formAction, isPending] = useActionState(addTodo, {
error: null,
title: "",
});
return (
<div>
<ul>
{optimisticTodos.map((todo) => (
<li key={todo.id}>
{todo.title}
{todo.sending && <small> (saving...)</small>}
</li>
))}
</ul>
<form action={formAction}>
<input name="title" defaultValue={state.title} aria-label="New item" />
<SubmitButton />
{state.error && <p role="alert">{state.error}</p>}
</form>
{isPending && <p>Working...</p>}
</div>
);
}Try it with "Buy milk" (it succeeds), then "fail please" (the item flashes, disappears, and the message appears), then an empty submit (the message appears and no "saving" item shows).
What happens, step by step
The order of events explains most of the design choices.
Four details in that sequence matter.
- Validation comes before the optimistic update. If you call
addOptimisticTodofirst and then reject the input, the user sees a flash of an item that was never going to be saved. - The pending flags flip on their own. You never call
setLoading(true). BothisPendinganduseFormStatus().pendingare true from submit until the async function settles. - The optimistic layer is temporary by design. It lasts only while the Action is in flight. When the Action ends,
optimisticTodosfalls back to whatevertodosis. If you did not updatetodos, the new item vanishes, even on a successful save. - The form resets after the Action finishes. Uncontrolled inputs return to their
defaultValue. Because the Action returnstitle: ""on success andtitleon failure,defaultValue={state.title}gives you "clear on success, keep on failure" with no extra code.
Why `startTransition` wraps `setTodos`
This line looks redundant, so it deserves an explanation:
startTransition(() => {
setTodos((current) => [...current, saved]);
});An Action runs inside a transition, but React only tracks that context up to the first await. A state update made after an await is a plain update, outside the transition. React could then render the new todos while the optimistic layer is still active. The optimistic reducer would run again on top of the new list, and the item would appear twice for a moment.
Wrapping the update in startTransition ties it to the same transition as the Action. React then commits the real data and removes the optimistic layer in one render. Use this pattern for any state update that follows an await inside an Action.
Two ways to read "pending"
The component above uses isPending from useActionState for the "Working..." line and useFormStatus inside SubmitButton. Both are shown on purpose.
isPendingis simplest when the component that owns the Action also renders the UI that depends on it.useFormStatusis for reusable pieces such as a submit button, a spinner, or a fieldset that you want to drop into any form without passing props.
useFormStatus has a limit that causes the most common bug in this area. It reads the status of the nearest parent <form>, so it must be called from a component rendered inside that form. If you call it in TodoApp, which renders the form, it reports pending: false forever, because TodoApp is not inside any form.
Submissions are queued
Actions dispatched through useActionState run one at a time, in the order they were submitted. If a user submits twice quickly, the second addTodo call receives the first call's returned state as previousState. It starts only after the first call has finished.
This is why the button disables itself during a submission. It is also why you should not rely on the disabled button as the only guard. The Enter key in the input, a second tab, or a direct call can still produce another submission. Make the Action safe to run twice, for example by checking previousState or asking the server to reject duplicates.
Choosing the return shape
The value your Action returns becomes state. A stable shape makes the JSX simpler. This chapter uses { error, title }, which gives three outcomes with the same two keys:
| Outcome | Returned value | Effect on the form |
|---|---|---|
| Validation failed | `{ error: "Title is required.", title: "" }` | Message shown, no request made |
| Server failed | `{ error: "The server rejected this item.", title }` | Message shown, input keeps the text |
| Success | `{ error: null, title: "" }` | Message cleared, input cleared |
Returning a different shape on each path is a common source of state.error is undefined bugs and awkward state?.error?.message chains. Pick one shape, and set every key on every path.
Expected failures such as bad input or a rejected request should be returned as state. Reserve throw for unexpected failures. An uncaught error inside an Action propagates to the nearest error boundary, which replaces your form with the fallback UI. In the example, the catch block turns the server's rejection into state so the form stays on screen.
Common mistakes
- Calling
addOptimisticTodooutside an Action. React warns that an optimistic update happened outside a transition. Call it only from inside the function you pass toaction,useActionState, orstartTransition. - Forgetting to update the real data. The optimistic item disappears when the Action ends. The real list must change before that point, or on the next fetch, or the item seems to vanish.
- Reading input values from state instead of
FormData. The form is uncontrolled here. Mixing inuseStatefor the same input duplicates the source of truth and fights with the automatic reset. - Putting the optimistic hook in a child that does not hold the data.
useOptimistictakes the real value as its first argument. Keep it in the component that owns that value, and pass the optimistic result down. - Using an unstable optimistic id. Optimistic items need a
key. The example usespending-${current.length}. If two optimistic items can exist at once, make sure their ids differ.
When to leave something out
You do not need all three hooks in every form. A settings form that saves quietly may need only useActionState. A "like" button needs useOptimistic and probably no error text. A search form that only reads data needs neither.
Add each hook for a reason you can state in one sentence. If you cannot, the form is simpler without it.
Exercise
In the TodoApp, a teammate moves useFormStatus() out of SubmitButton and into TodoApp to disable the button with disabled={pending}. The button never disables during a save. Why, and what is the smallest fix?
Show answer
useFormStatus reads the status of a parent <form>. TodoApp renders the form but is not inside it, so the hook always reports pending: false. The smallest fix is to move the hook back into a child component rendered inside the form (such as SubmitButton). Alternatively, use the isPending value returned by useActionState in TodoApp, which works because the component that owns the Action can read it directly.
Exercise
A user submits "Buy milk" and the save succeeds, but the item flashes twice for one frame. The code calls setTodos(...) directly after await saveTodo(title). What causes the flash, and how do you fix it?
Show answer
The update after await is no longer part of the Action's transition, so React can render the new todos while the optimistic layer is still applied. The optimistic reducer then adds the item on top of the real list, which shows it twice until the Action ends. Wrapping the update in startTransition(() => setTodos(...)) ties it to the same transition, so the real data and the removal of the optimistic layer commit together.
Exercise
Change the Action so that a title already in the list is rejected with the message "Already on the list." without making a request and without any optimistic item. Where in addTodo does the check go, and what must it return?
Show answer
Put the check after the empty and length validation and before addOptimisticTodo(title), comparing against the real todos (for example todos.some((t) => t.title === title)). Return { error: "Already on the list.", title } so the shape matches the other paths and the input keeps the user's text. Checking before the optimistic call prevents a flash of an item that will never be saved.