Handle form actions with useActionState
Run a form action with React 19 useActionState to get the last result and a pending flag, without writing onSubmit and loading state by hand.
Form handling usually means preventing default, tracking pending and storing the error. React 19 lets a form take a function as its action, and useActionState keeps the result.
import { useActionState } from 'react';
import { subscribe } from './api.js';
async function subscribeAction(previousState, formData) {
const email = formData.get('email');
if (!email.includes('@')) {
return { ok: false, message: 'Enter a valid email address' };
}
await subscribe(email);
return { ok: true, message: `Subscribed ${email}` };
}
export function Subscribe() {
const [state, formAction, isPending] = useActionState(subscribeAction, null);
return (
<form action={formAction}>
<input name="email" type="text" />
<button disabled={isPending}>Subscribe</button>
{state && <p>{state.message}</p>}
</form>
);
}(submit "nope") -> Enter a valid email address
(submit "[email protected]") -> Subscribed [email protected]React calls the action with the previous state and the form's FormData. Whatever it returns becomes the new state, and isPending is true until the promise settles. The form also resets itself after a successful action. See useActionState.
In React 19 this hook replaces useFormState from react-dom. Keep it for forms, and use plain state for values not tied to a submit.