Sub topic 1
React 19 Actions and Form Actions: Async Transitions
Prerequisites
This chapter assumes solid knowledge of React function components, hooks, JSX, async functions, fetch, and the browser FormData API. You should also know the difference between controlled and uncontrolled inputs.
Async transitions and pending state with `useTransition`
A transition tells React that an update is less urgent than direct interaction, such as typing. React 19 also lets a transition run an asynchronous function. The function passed to startTransition is called an Action.
useTransition returns isPending and startTransition. React keeps isPending true while the asynchronous Action runs.
import { useState, useTransition } from "react";
export function UpdateName() {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
function handleSubmit() {
startTransition(async () => {
const response = await fetch("/api/name", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
if (!response.ok) {
setError("Could not update the name.");
return;
}
setError(null);
});
}
return (
<div>
<input value={name} onChange={(event) => setName(event.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
{isPending ? "Updating..." : "Update"}
</button>
{error && <p role="alert">{error}</p>}
</div>
);
}What an Action is in React 19
An Action is a function that React runs as part of a transition. It commonly performs a mutation, waits for a server response, and updates component state. Actions give React a consistent place to track pending work.
An Action does not automatically validate input, handle every error, or update your database. Your function still needs to do those jobs.
> callout note > Disable controls or show progress while isPending is true. This prevents duplicate submissions and tells users that their request is running.
Passing a function to `<form action>`
React forms can receive a function through the action prop. React calls that function when the form submits and passes a FormData object containing the named controls.
export function SearchForm() {
async function search(formData) {
const query = String(formData.get("query") ?? "").trim();
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
console.log(await response.json());
}
return (
<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
);
}Each value must have a name, or it will not appear in FormData.
Exercise
What value does formData.get("query") return in the example?
Show answer
It returns the current value of the input whose name is "query".