Actions

Async transitions for forms: pending, optimistic, settled.

Builds on Transitions, Forms.

The forms chapter handled submission the classic way: an onSubmit handler, preventDefault, and a few useState flags for "submitting" and "error". The transitions chapter then showed that startTransition accepts an async function and keeps isPending true across every await. Put those two together and you get React 19's Actions: async transitions wired into forms, with hooks for the pending state, the result, and an optimistic preview of the result before the server answers.

The running example adds a book to the reading list through the fake API, fakeFetch("/books", { method: "POST" }), and shows it in the list immediately.

The problem: the submit handler you've written fifty times#

Here's adding a book by hand. It works, mostly. Tick Make the request fail and submit.

Adding a book, by hand
import { useState, type FormEvent } from "react";
import { books as seed, fakeFetch } from "guide-tools";

type Book = { id: number; title: string };

export default function App() {
  const [books, setBooks] = useState<Book[]>(seed.slice(0, 3));
  const [title, setTitle] = useState("");
  const [fail, setFail] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    if (isSaving) return; // guard against double submits
    setIsSaving(true);
    setError(null);
    try {
      const saved = (await fakeFetch("/books", { method: "POST", body: { title }, delay: 1000, fail })) as Book;
      setBooks((bs) => [...bs, saved]);
      setTitle("");
      setIsSaving(false);
    } catch (err) {
      setError((err as Error).message);
      // Bug: forgot setIsSaving(false) here.
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" />{" "}
      <button disabled={isSaving}>{isSaving ? "Saving..." : "Add book"}</button>
      <label style={{ display: "block" }}>
        <input type="checkbox" checked={fail} onChange={(e) => setFail(e.target.checked)} /> Make the request fail
      </label>
      {error ? <p style={{ color: "#a0461f" }}>{error}</p> : null}
      <ul>
        {books.map((b) => (
          <li key={b.id}>{b.title}</li>
        ))}
      </ul>
    </form>
  );
}

After a failure the button says "Saving..." forever, because one code path forgot to clear the flag. That's the shape of the problem. Every form carries the same bookkeeping: prevent the default, track pending, clear and set errors, reset the fields, guard double submits, and keep each of those consistent on every path, including the error path nobody tests. And the user still stares at nothing for a full second before the new book appears.

Actions are async transitions#

React's name for "a function that runs inside a transition" is an Action. You already met the mechanism:

const [isPending, startTransition] = useTransition();

function addBook(title: string) {
  startTransition(async () => {
    const saved = await fakeFetch("/books", { method: "POST", body: { title } });
    startTransition(() => setBooks((bs) => [...bs, saved]));
  });
}

The inner startTransition is the rule from that chapter: a setter after an await has to be wrapped again to stay part of the transition. isPending is true from the first line to the moment the final state is on screen, on every path. If the function throws, the transition still ends and isPending goes back to false. There's no flag to forget.

Everything else in this chapter is that idea, plugged into the places forms need it.

<form action={fn}> React 19#

In React DOM, a <form>'s action prop can be a function. On submit, React prevents the browser's navigation, builds a FormData from every field that has a name, and calls your function with it inside a transition. So the function is an Action, and it can be async.

A form whose action is a function

Type a title and use either button. Watch the field after the save.

import { startTransition, useState } from "react";
import { fakeFetch } from "guide-tools";

export default function App() {
  const [shelf, setShelf] = useState<string[]>([]);
  const [wishlist, setWishlist] = useState<string[]>([]);

  async function addToShelf(formData: FormData) {
    const title = String(formData.get("title"));
    await fakeFetch("/books", { method: "POST", body: { title }, delay: 500 });
    startTransition(() => setShelf((s) => [...s, title]));
  }

  async function addToWishlist(formData: FormData) {
    const title = String(formData.get("title"));
    await fakeFetch("/books", { method: "POST", body: { title, wishlist: true }, delay: 500 });
    startTransition(() => setWishlist((w) => [...w, title]));
  }

  return (
    <form action={addToShelf}>
      <input name="title" placeholder="Title" required />{" "}
      <button type="submit">Add to shelf</button>{" "}
      <button formAction={addToWishlist}>Add to wishlist</button>
      <p>Shelf: {shelf.join(", ") || "empty"}</p>
      <p>Wishlist: {wishlist.join(", ") || "empty"}</p>
    </form>
  );
}

Three things to notice:

  • No onSubmit, no preventDefault, no value/onChange. The input is uncontrolled, and the Action reads it from FormData. That's the style Actions are designed for.
  • formAction on a button overrides the form's action for that button only. One form, two outcomes, no "which button was clicked" logic.
  • The field cleared itself. After an Action passed to action or formAction finishes without throwing, React resets the form's uncontrolled fields to their default values (like calling form.reset()). Controlled fields aren't touched, since their value is your state. If the Action throws, there's no reset. React 19.3 Since 19.3, React also fires the form's onReset handler when it resets the form automatically, so state tied to the fields can be cleared in the same place as for a manual reset.

When a function is passed to action or formAction, React always submits with POST semantics, whatever the method prop says. And action can still be a URL string, in which case the form behaves like plain HTML.

useFormStatus: pending state without prop drilling#

A submit button usually wants to know whether its form is submitting, and the button is often a reusable component far from the form's logic. useFormStatus from react-dom reads the status of the nearest parent <form>:

import { useFormStatus } from "react-dom";

function SubmitButton({ children }: { children: string }) {
  const { pending, data } = useFormStatus();
  return (
    <button type="submit" disabled={pending}>
      {pending ? `Saving "${data?.get("title")}"...` : children}
    </button>
  );
}

It returns pending (is the form's Action running), data (the FormData being submitted, or null), method and action. It works like a context that only <form> provides, which has one sharp consequence: it must be called in a component rendered inside the form. Called in the component that renders the <form> itself, it looks for a form above, finds none, and pending is always false. You'll fix exactly that bug in an exercise.

useActionState: an Action with a result#

Most forms need a result from the Action: a validation error, a success message, the saved record. useActionState wraps an Action and keeps its last return value as state:

const [state, formAction, isPending] = useActionState(action, initialState);
  • Your action receives (previousState, formData), note the extra first argument compared with a plain form action, and returns (or resolves to) the next state.
  • formAction is what you pass to <form action> or a button's formAction. You can also call it yourself, but then you must call it inside startTransition, or React logs an error in development and isPending won't update.
  • isPending is true while any dispatched Action for this hook is running.
  • Dispatches are queued: React runs them one after another, each receiving the previous one's result. That's what makes previousState meaningful, and it means two quick submits can't race.

It's useReducer for async work, where the reducer is allowed side effects. Expected failures, like validation, go in the returned state. Unexpected ones you throw (more on that below).

useOptimistic: show the result before it exists#

The book still takes a second to appear. Usually the server will accept it, so you can show it now and reconcile when the answer comes back. useOptimistic gives you a temporary version of some state that only exists while an Action is pending:

const [optimisticBooks, addOptimisticBook] = useOptimistic(
  books, // the real state
  (current, newBook: Book) => [...current, { ...newBook, pending: true }], // optional reducer
);
  • While no Action is pending, optimisticBooks is just books.
  • Inside an Action, addOptimisticBook(x) makes optimisticBooks show the reducer's result immediately.
  • When the Action's transition ends, the optimistic value is thrown away and you see the real books again, whatever they are by then. On success that's the list with the saved book in it. On failure it's the old list, so the optimistic row simply disappears. There's no rollback code to write.
  • The setter must be called inside an Action or transition. Called outside, React warns and the optimistic value flashes for a single render.

With a reducer, if the real books change while the Action is pending, React re-runs the reducer against the new base, so the optimistic row stays on top of fresh data.

The reading list: add a book with an Action#

Here's everything together. The list is the Action's state, the optimistic list sits on top of it, and the button reads the form status. Try a normal add, then tick Make the request fail and try again.

Reading list: an Action with an optimistic update
import { useActionState, useOptimistic } from "react";
import { useFormStatus } from "react-dom";
import { books as seed, fakeFetch } from "guide-tools";

type Book = { id: number; title: string; pending?: boolean };
type State = { books: Book[]; error: string | null; draft: string };

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending}>
      {pending ? "Adding..." : "Add book"}
    </button>
  );
}

export default function App() {
  const [state, formAction] = useActionState(addBook, {
    books: seed.slice(0, 3).map(({ id, title }) => ({ id, title })),
    error: null,
    draft: "",
  });

  const [optimisticBooks, addOptimisticBook] = useOptimistic(state.books, (current, book: Book) => [
    ...current,
    { ...book, pending: true },
  ]);

  async function addBook(prev: State, formData: FormData): Promise<State> {
    const title = String(formData.get("title") ?? "").trim();
    if (!title) return { ...prev, error: "Give the book a title.", draft: "" };

    addOptimisticBook({ id: -1, title });
    try {
      const saved = (await fakeFetch("/books", {
        method: "POST",
        body: { title },
        delay: 1200,
        fail: formData.get("fail") === "on",
      })) as Book;
      return { books: [...prev.books, saved], error: null, draft: "" };
    } catch {
      return { ...prev, error: `Couldn't save "${title}". Try again.`, draft: title };
    }
  }

  return (
    <form action={formAction}>
      <input name="title" placeholder="Title" defaultValue={state.draft} /> <SubmitButton />
      <label style={{ display: "block" }}>
        <input type="checkbox" name="fail" /> Make the request fail
      </label>
      {state.error ? <p style={{ color: "#a0461f" }}>{state.error}</p> : null}
      <ul>
        {optimisticBooks.map((b) => (
          <li key={b.id} style={{ opacity: b.pending ? 0.5 : 1 }}>
            {b.title} {b.pending ? <small>(saving...)</small> : null}
          </li>
        ))}
      </ul>
    </form>
  );
}

Compare it with the hand-written version. There's no isSaving flag to forget, no preventDefault, no manual reset, no rollback, no double-submit guard (the Actions are queued). The failure path returns state like the success path does. And because a successful Action resets the form, the failure path returns the draft so the input's defaultValue brings the typed title back after the reset.

An Action with an optimistic update
What the user seesDuneAdd bookRefactoringThinking in SystemsHook valuesisPendingfalseoptimistic= state (2 books)state2 booksoptimistic = state, unlessan Action is pending
Step 1 of 5

Idle. The reading list shows two books and the user has typed a title. Nothing is pending.

Errors in Actions#

You have two channels, and choosing between them is a design decision, not a style preference.

Return expected errors. Validation messages, "that title already exists", a failed request you want to retry inline. Return them as part of the state from useActionState and render them. The Action completed normally, so the form resets (return the draft if you need it back, as above).

Throw unexpected errors. A bug, an impossible state, a request you can't recover from inline. When an Action passed to a form or to startTransition from useTransition throws, React shows the nearest error boundary. With useActionState, it also cancels every queued Action for that hook. The transition still ends, so optimistic state reverts, and the form is not reset.

async function addBook(prev: State, formData: FormData) {
  const title = String(formData.get("title") ?? "");
  if (!title) return { ...prev, error: "Give the book a title." }; // expected: return it
  const saved = await saveBook(title); // a 500 here throws: error boundary shows
  return { ...prev, books: [...prev.books, saved], error: null };
}

One exception to remember: the standalone startTransition imported from react has no component attached, so an error thrown in it can't reach an error boundary. Catch those yourself.

requestFormReset: the reset, without the form action#

Sometimes you keep your own onSubmit (to read the event, call an API with custom options, or integrate a form library) but still want React's "reset after the Action" behavior. requestFormReset(form) from react-dom asks React to reset a form it renders once the current transition finishes:

import { startTransition } from "react";
import { requestFormReset } from "react-dom";

function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
  e.preventDefault();
  const form = e.currentTarget;
  const formData = new FormData(form);
  startTransition(async () => {
    requestFormReset(form);
    await saveBook(formData);
  });
}

Call it inside the transition. Outside one, React warns in development and resets immediately. Like the automatic reset, it only resets uncontrolled fields.

Pitfalls#

Check your understanding#

Fix itThe button never says Adding

The submit button should be disabled and say "Adding..." while the book is saving. It never changes. Fix it. The checks submit a title and look for the pending label, then for the new list item.

import { startTransition, useState } from "react";
import { useFormStatus } from "react-dom";
import { fakeFetch } from "guide-tools";

export default function App() {
  const [titles, setTitles] = useState<string[]>([]);
  const { pending } = useFormStatus();

  async function addBook(formData: FormData) {
    const title = String(formData.get("title"));
    await fakeFetch("/books", { method: "POST", body: { title }, delay: 800 });
    startTransition(() => setTitles((t) => [...t, title]));
  }

  return (
    <form action={addBook}>
      <label>
        Title <input name="title" />
      </label>{" "}
      <button type="submit" disabled={pending}>
        {pending ? "Adding..." : "Add"}
      </button>
      <ul>
        {titles.map((t) => (
          <li key={t}>{t}</li>
        ))}
      </ul>
    </form>
  );
}
PredictWhen the save fails

The list starts with two books. The user submits "Dune", and the request fails after one second. The Action throws (no try/catch), and there's an error boundary around the whole form. Describe what the user sees at 0 ms, during the second, and after it.

async function addBook(formData: FormData) {
  const title = String(formData.get("title"));
  addOptimisticBook({ id: -1, title });
  const saved = await fakeFetch("/books", { method: "POST", body: { title }, fail: true, delay: 1000 });
  startTransition(() => setBooks((bs) => [...bs, saved]));
}
Build itValidate with useActionState

Finish the Action so an empty title doesn't add anything and instead shows Title is required under the form. A valid title should be added and clear the message. The checks submit an empty form, then a real title.

import { useActionState } from "react";
import { sleep } from "guide-tools";

type State = { titles: string[]; error: string | null };

async function addTitle(prev: State, formData: FormData): Promise<State> {
  const title = String(formData.get("title") ?? "").trim();
  // TODO: if title is empty, keep the titles and return an error instead
  await sleep(300);
  return { titles: [...prev.titles, title], error: null };
}

export default function App() {
  const [state, formAction, isPending] = useActionState(addTitle, { titles: [], error: null });
  return (
    <form action={formAction}>
      <label>
        Title <input name="title" />
      </label>{" "}
      <button type="submit" disabled={isPending}>
        Add
      </button>
      {/* TODO: show state.error */}
      <ul>
        {state.titles.map((t, i) => (
          <li key={i}>{t}</li>
        ))}
      </ul>
    </form>
  );
}
Quick checkAfter a successful submit

A form has action={save}, one uncontrolled input with defaultValue='Draft', and one controlled input. The user edits both and save() resolves. What happens?

Explain it out loudWhat is an Action?

An interviewer asks: "What are Actions in React 19, and why would you use them instead of an onSubmit handler?"

Interview angle

Say it in 30 seconds

In React 19 an Action is a function that runs inside a transition, usually async. React tracks it, so the pending state covers its whole life, errors included. A form's action prop takes such a function: React calls it with FormData in a transition and resets uncontrolled fields when it succeeds. useFormStatus gives a nested button the pending state, useActionState keeps the Action's result as state and queues submissions, and useOptimistic shows the expected result immediately and discards it when the Action ends, so failed requests roll back on their own.

What is an Action in React 19?

basic

What does React do when a form's action prop is a function?

intermediate

How does useOptimistic work, and how does it roll back a failed update?

intermediate

Why does useFormStatus always return pending: false in some components?

basic

How should you handle errors in Actions?

senior

A user double-clicks submit on a form using useActionState. What happens?

senior

Recap#

  • An Action is a function run in a transition. isPending covers its whole life, including awaits and errors.
  • <form action> and formAction call your function with FormData in a transition, and reset uncontrolled fields after a successful Action.
  • useFormStatus gives a component inside a form its pending state and data. It never sees the form rendered by its own component.
  • useActionState keeps the Action's result as state, passes the previous state in, and queues dispatches. Return expected errors; throw unexpected ones to an error boundary.
  • useOptimistic shows a temporary result while an Action is pending and drops it when the Action ends, so failures roll back by themselves. requestFormReset brings the reset to hand-written submit handlers.

Sources#