Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 132 ยท Forms and Actions

useFormStatus and useOptimistic

Learn useFormStatus to read a parent form's pending state from child components, and useOptimistic to show instant UI updates that roll back when an action fails.

Two React 19 hooks finish the forms story. useFormStatus lets any component inside a <form> ask "is my form submitting right now?", so a submit button can disable itself without props. useOptimistic lets you show the result of an action immediately, before the server has answered, and quietly puts things back if the server says no. Both exist because async actions have a waiting period, and good interfaces handle that wait honestly: either by saying "working..." or by pretending the work is already done and fixing it if the pretence was wrong.

Both hooks build on form actions and sit nicely next to useActionState. useFormStatus is imported from react-dom; useOptimistic comes from react.

useFormStatus: the form's pending state, anywhere inside it

In the previous lessons we saw that a flag you set yourself inside an async action does not render while the action is pending. useFormStatus is the tool built for this. It returns an object describing the parent <form>'s current submission:

Field While the form is submitting Otherwise
pending true false
data the FormData being submitted null
method 'get' or 'post' null
action the action function (or URL) null

The most common use is a reusable submit button:

JSX
import { useFormStatus } from 'react-dom';

function SubmitButton({ children }) {
  const { pending } = useFormStatus();
  return <button type="submit" disabled={pending}>{pending ? 'Working...' : children}</button>;
}

Drop <SubmitButton>Save</SubmitButton> into any form of your app and it just works, with no prop drilling. The demo below also records what the hook reported while the form was submitting, so you can read data and method after the fact.

A submit button that knows its form is pending

Press Save profile. For 300 ms the button reads "Saving..." and is disabled; the line below it then shows name=Ada, method=get, action is a function. The data really is the FormData of that submission, which is handy for showing "Saving Ada..." in a message. method is get because we did not set method="post" on the form; for function actions it does not matter.

The rule that trips everyone: child, not parent

useFormStatus reports on a form that is above the component calling it. A component cannot read the status of a form it renders itself. Compare the two forms below: they are identical except where the hook is called.

useFormStatus in the wrong place (pitfall)

Click both buttons. The "right" one changes to "Saving..." for 300 ms; the "wrong" one never changes, and the console only ever logs WrongForm render, pending = false. React gives no warning, so remember the rule: extract the button (or any status-aware part) into its own component and render it inside the form.

Disabling a whole form while it submits

A second helpful child is a wrapper that disables every control. A <fieldset disabled> disables all the form controls inside it with one attribute, and the browser also skips them when building the form data (disabled controls are not submitted), which is another reason to read values in the action as it starts.

JSX
function FormFields({ children }) {
  const { pending } = useFormStatus();
  return <fieldset disabled={pending} style={{ border: 0, padding: 0 }}>{children}</fieldset>;
}

Use it as <form action={...}><FormFields>...inputs...</FormFields><SubmitButton /></form>. Disabling inputs during a save prevents the user from editing data that is already on its way out.

useOptimistic: show the result first

Networks are slow, but most requests succeed. Optimistic UI assumes success: when the user adds a comment, the comment appears at once, marked "sending", and the server's real answer replaces it later. If the request fails, the optimistic item disappears. The interface feels instant, and it stays correct.

JSX
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);
  • state is the real value, from useState, props or a server. It is the source of truth.
  • updateFn(currentState, optimisticValue) is a pure function that returns what the UI should look like with the optimistic change applied. It is just like a reducer.
  • optimisticState is what you render. Normally it equals state.
  • addOptimistic(value) applies updateFn for the duration of an action. You must call it inside an action (a form action, or a function passed to startTransition).

The mental model is a temporary overlay. While the action runs, React renders updateFn(state, value). When the action finishes, React throws the overlay away and renders the real state. If, by then, you have updated the real state with the saved item, the user sees no change at all, only the "sending" label vanishing. If you did not (because it failed), the item is gone.

An optimistic message list

Press Send. The message appears immediately, dimmed with "(sending...)". After 300 ms the label disappears and the message is at full strength: the optimistic overlay was dropped, and the list now comes from messages. There is no flicker, because React swaps the overlay for the real state in the same render in which setMessages lands.

Rollback on failure

Rollback needs no code of its own. If the action ends without adding the item to the real state, for instance because the server rejected it, the overlay vanishes and the item vanishes with it. What you should add is an explanation. The next demo rejects any message that contains the word fail:

Optimistic update that rolls back

Send the default text and the dimmed message appears, then after 300 ms it disappears and the red explanation shows. Change the text to This works and send again: it appears, dims, and stays. In a real app you would also give the user a way to retry, for example by keeping their text.

Setting versus changing: make optimistic updates absolute

Optimistic updates fall apart when the update function means "add one" and several are in flight, because each overlay is re-applied on top of whatever the real state is at that moment. If two "+1" actions finish at slightly different times, you can see the count jump (we saw a render showing 4 when the real total was 2, for a single frame). The reliable fix is to let the update say what the value should be, not how much to change it by. A "liked" toggle is the classic case:

A like button with an absolute optimistic value

Click once: the button flips to "Liked (42)" immediately and "Confirmed by the server" updates 250 ms later. Click twice quickly and the button follows each click, ending where you stopped. Note that this component uses startTransition(async () => ...) instead of a form, which is legal: useOptimistic only needs an action context.

Ordering, and what happens with several updates

When several optimistic updates are pending, React applies them in the order you called addOptimistic, each on top of the last, and removes all of them when their actions complete and the real state has caught up. If your updateFn appends to a list, a second message appears below the first, and the order is stable even if the server answers out of order. That is also why the id of an optimistic item must be unique but temporary: use pending-N or a client-generated id, and replace it with the server id when the real item arrives (as in the chat above). Remember a few more points:

  • The real state must change in the same action. If you update it later (after the transition ended), the optimistic item disappears for a moment, and the user sees a flicker before the real item shows up.
  • Never rely on optimistic data for anything permanent. It is a picture, not a record. Do not write it to a database, a cache or another piece of state.
  • Keep updateFn pure. No fetch, no random ids that change on every render, no mutation of current.
  • Do not use it for destructive or irreversible work such as payments. Show a real pending state there.

Patterns: likes, todos, comments

Feature Optimistic value Rollback shows
Like / follow / bookmark the new boolean, plus a derived count the old state, plus an error toast
Add todo the new item with sending: true the item disappears, the text can be restored
Toggle todo done the list with the flag flipped the checkbox flips back
Delete item the list without the item (or the item marked "removing") the item reappears
Post comment the comment at the end of the list, dimmed the comment disappears with an inline error

For lists, a nice touch is to mark optimistic items (dimmed, a small "sending" label, or aria-busy) so users know the data is not saved yet. Be careful with disabled buttons on such items: an item that has no server id cannot be edited or deleted yet.

useFormStatus and useOptimistic together

The two hooks solve different problems and combine well. useOptimistic shows the result early; useFormStatus can show the in-flight state of the button or of a "Saved" indicator. With optimistic updates you often show less pending UI, because the list already moved on. For anything where being wrong is costly, prefer useFormStatus and wait for the real answer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where must a component that calls useFormStatus be rendered?

    useFormStatus reads the status of a parent form. A component that renders the form itself has no parent form, so pending is always false.
  2. 2. What does useOptimistic return?

    You get the value to render (real state plus any optimistic overlay) and a function that adds an optimistic change inside an action.
  3. 3. An action calls addOptimistic and then the server fails, so the real state is never updated. What does the user see?

    The optimistic value is a temporary overlay that exists only while the action runs. Without a matching change to real state it vanishes, which is the rollback.
  4. 4. Why prefer an optimistic update that sets a value (liked: true) over one that adds a delta (+1)?

    Each overlay is re-applied on top of whatever the real state currently is, so relative changes can double-count while updates overlap. Absolute values cannot.
  5. 5. Which of these is a good rule for the update function passed to useOptimistic?

    Like a reducer, the update function runs during rendering and must be pure: no network, no mutation.

Summary

  • useFormStatus() (from react-dom) returns { pending, data, method, action } for the parent form; call it in a child such as a submit button.
  • Calling it in the component that renders the form gives pending: false forever, without a warning.
  • A <fieldset disabled={pending}> child can disable a whole form during submission.
  • useOptimistic(state, updateFn) returns [optimisticState, addOptimistic]; call addOptimistic inside an action or startTransition.
  • The optimistic value is a temporary overlay that is dropped when the action ends: update the real state in the same action to keep the change, or do not to roll back.
  • Write updateFn as a pure function and prefer absolute values (a toggle's final state) over deltas.
  • Mark optimistic items visually, give them temporary ids and always explain failures to the user.
  • Skip optimistic UI for irreversible actions such as payments; show a real pending state instead.

Next: Uncontrolled Forms, File Inputs and Complex Forms