useActionState
React 19 forms.
React nineteen made forms simpler. A form's action can now be a function, even an async one. And use action state tracks its result, and whether it's still running.
- Simpler forms
- Actions
- useActionState
A newsletter action
In React nineteen, a form's action can be a function. Use action state wraps an async action, and gives back its latest result, plus a pending flag. The action gets the form data, and returns the new state. The button is disabled while it's pending. We submit an email. Run it.
import { useActionState } from "react";
const wait = ms => new Promise(r => setTimeout(r, ms));
async function subscribe(previous, formData) {
await wait(300);
const email = formData.get("email");
if (!email.includes("@")) return { error: "Enter a valid email" };
return { message: `Subscribed ${email}` };
}
export default function App() {
const [state, formAction, isPending] = useActionState(subscribe, {});
return (
<form action={formAction}>
<input id="e" name="email" placeholder="Email" />
<button id="go" disabled={isPending}>{isPending ? "Joining..." : "Join"}</button>
{state.error && <small>{state.error}</small>}
{state.message && <p>{state.message}</p>}
</form>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"type": "#e", "text": "sam@example.com"}, {"click": "#go"}, {"wait": 600}]What you get
No on submit, no prevent default, and no loading state to manage by hand. The inputs don't even need to be controlled, because the action reads the form data. React also resets the form after the action finishes.
| key | value |
|---|---|
| No | preventDefault |
| No | manual loading state |
| Reads | FormData |
| Resets | the form |
Summary
Use action state runs a form action, and tracks its result and pending state. Next, use optimistic.
Key takeaways- <form action>
- useActionState
- isPending