Sub topic 2
What an Action is in React 19
This chapter assumes you know function components, useState, and useEffect. It also assumes you can read async/await code and know what fetch returns. The previous chapter showed that startTransition accepts an async function and that isPending stays true while it runs. This chapter names that pattern, explains what React does with it, and lists the features built on it.
The definition
An Action is a function that you give to React so that React runs it inside a transition. The function usually performs a mutation. A mutation is any operation that changes data, such as saving a profile, posting a message, or deleting a row. The function is often async.
React 19 does not add a new Action type or a new API called action(). "Action" is a convention. If a function is passed to one of the places listed below, React treats it as an Action. By convention, the names of such functions or props end in "Action", or the prop is called action.
Before React 19, you had to track the state of a mutation yourself. A typical component had an isPending flag, an error value, and a try/catch block with setIsPending(false) in a finally clause. Each component repeated this code, and each copy had its own bugs. Actions move that bookkeeping into React.
What React does for you
When React runs a function as an Action, it provides the following.
- Pending state. React reports that work is in progress from the start of the Action until the async function settles. You read this as
isPendingfromuseTransition, aspendingfromuseFormStatus, or as the third value fromuseActionState. - Error handling. If the Action throws, the error propagates to the nearest error boundary instead of disappearing as an unhandled promise rejection. Errors you expect, such as "name is required", should be returned as values. The "Handling validation errors and failures" chapter covers this.
- Optimistic updates.
useOptimisticlets you show the expected result right away. React discards the temporary value when the Action finishes. - Form handling. A function passed to
<form action>runs as an Action. React supplies theFormDataand resets uncontrolled inputs when the Action succeeds. - Responsive UI. Because the Action runs in a transition, the work does not block urgent updates such as typing. A transition's UI update can also be interrupted if something more urgent arrives.
The diagram shows the order of events for one Action.
Where Actions come from
Several APIs accept a function and run it as an Action.
| Entry point | How you pass the function | What you read back |
|---|---|---|
| `useTransition` | `startTransition(async () => { ... })` | `isPending` |
| `<form>` | `<form action={fn}>` | `useFormStatus().pending` in a child component |
| `<button>` or `<input type="submit">` | `formAction={fn}` | Same as above |
| `useActionState` | `useActionState(fn, initialState)` | `[state, formAction, isPending]` |
| `useOptimistic` | Call the setter inside an Action | The temporary value |
Later chapters cover each entry point in detail. The key point is that they share one model. The useTransition hook is the simplest of them, so the next sections use it.
A complete example with useTransition
This component sends a name to a server and shows an error if the request fails.
import { useState, useTransition } from "react";
async function updateName(name) {
const response = await fetch("/api/name", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
if (!response.ok) {
return "Could not update the name.";
}
return null;
}
export function UpdateName() {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
function handleSubmit() {
startTransition(async () => {
const message = await updateName(name);
if (message) {
setError(message);
return;
}
setError(null);
});
}
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
}The function passed to startTransition is the Action. React sets isPending to true when the function starts. React sets it back to false after the returned promise settles and the resulting state updates are committed. The button is disabled during that period, so the user cannot send the same request twice by double-clicking.
Notice that the Action returns an error message instead of throwing. The caller decides how to present the message. This pattern appears in every later chapter.
What counts as part of the transition
An Action has an important limit: React can only mark state updates as part of the transition while it is running your function synchronously. An await ends the synchronous part. Code after an await runs later, as a normal continuation, and the updates it makes are ordinary updates, not transition updates.
For this reason, the React documentation recommends wrapping state updates that follow an await in another startTransition call. The example above works without this, because the updates it makes after the await are small and urgent. The wrapping matters when an update after the await causes a heavy re-render or should not replace content that is already visible with a loading fallback.
import { useState, useTransition } from "react";
async function loadReport(id) {
const response = await fetch(`/api/reports/${encodeURIComponent(id)}`);
return response.json();
}
export function ReportViewer({ id }) {
const [report, setReport] = useState(null);
const [isPending, startTransition] = useTransition();
function handleRefresh() {
startTransition(async () => {
const data = await loadReport(id);
// This line runs after an await, so wrap the update again.
startTransition(() => {
setReport(data);
});
});
}
return (
<section>
<button onClick={handleRefresh} disabled={isPending}>
{isPending ? "Refreshing..." : "Refresh"}
</button>
{report && <pre>{JSON.stringify(report, null, 2)}</pre>}
</section>
);
}Two versions of startTransition
React exports a standalone startTransition function, and useTransition returns its own copy.
import { startTransition } from "react"runs a function as a transition, but gives you no pending flag. Use it where a hook is not available.- The
startTransitionfromconst [isPending, startTransition] = useTransition()also providesisPending. Use it when the UI should reflect the pending state.
Both accept async functions in React 19. Only the hook version tells your component that the work is running.
What an Action is not
Some misunderstandings are common at this stage.
- An Action is not a Server Action in the sense of "code that runs on a server". Many Actions run entirely in the browser, like the examples above. Server Functions, covered near the end of this tutorial, are one way to write an Action that runs on the server.
- An Action is not automatically cancelled. If the user navigates away or triggers a second Action, React does not abort your
fetch. If cancellation matters, pass anAbortSignaltofetchyourself. - An Action does not validate anything. React does not know your business rules. You write the checks and decide what to return.
- The return value of the function you pass to
startTransitionis ignored. If you need a result in the UI, store it withsetState, or useuseActionState, which exists for this purpose.
Why this model matters for the rest of the tutorial
Every later chapter is a variation on one sequence: a user triggers a function, React runs it in a transition, and React exposes a pending flag. The hooks differ only in what they add.
<form action>addsFormDataand automatic reset.useFormStatuslets a child component read the form's pending flag without props.useActionStatekeeps the last result of the Action.useOptimisticadds a temporary value.- Server Functions run the Action on a server.
If you remember the definition, you can predict how each of these behaves. For example, useOptimistic reverts when the Action ends because the optimistic value is only valid while the transition is pending.
Exercise
A teammate writes an Action with startTransition(async () => { const data = await save(); setResult(data); }). The page feels fine, but a large list re-renders when setResult runs, and typing in an input becomes sluggish at that moment. What is the likely cause, and how do you fix it?
Show answer
The setResult call runs after an await, so React does not treat it as a transition update. It is an ordinary, urgent update, and the large re-render blocks typing. Wrap the update in a second transition: startTransition(() => { setResult(data); }), placed after the await inside the async function.
Exercise
Which two statements about Actions are true? (1) React cancels the fetch inside an Action when the component unmounts. (2) An error thrown inside an Action propagates to the nearest error boundary. (3) A function passed to <form action> is run as an Action. (4) The value returned from the function passed to startTransition is available as isPending.
Show answer
Statements 2 and 3 are true. React does not cancel a fetch for you, so statement 1 is false. isPending is a boolean flag that reports whether the Action is running, not the function's return value, so statement 4 is false.