React 19 adds support for using async functions in [[20221003041754-react-transitions]]. useTransition
can better handle the pending state for you.
In the below example, the async transition will immediately set the isPending
state to true, make the async request, then set isPending
to false.
function UpdateName({}) {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
const handleSubmit = () => {
startTransition(async () => {
const error = await updateName(name);
if (error) {
setError(error);
return;
}
redirect("/path");
})
};
return (
<div>
<input value={name} onChange={(event) => setName(event.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
}
By convention, these async transitions are referred to as actions. They can better handle pending state, optimistic updates, error handling, and forms.