
React 19 Form Actions: Drop the isLoading Boilerplate
- كاتب موثّق
- React 19
محتويات المقال
isLoading and error. One afternoon the invite API times out and throws. The setIsLoading(false) after the await never runs, and the button says "Sending…" until someone reloads the page. Another form in the same app copied the pattern but forgot setError(null), so an old error stays on screen after a retry succeeds. Neither bug is about invites. Both live in plumbing that every form rewrites.
The common misconception
onSubmit handler that calls e.preventDefault(), a state variable per field, and isLoading and error states that you set by hand before and after the await.
action prop is only for Server Functions in a framework. The half that's true: the UI does need a pending state and somewhere to put errors. What changed is who keeps them in sync.
What actually happens
A function in action becomes an Action
action prop. On submit, React calls it with the form's FormData, and the function may be async. It runs in a , so unlike onSubmit there's no e.preventDefault() to remember, and once it succeeds, React resets the form's uncontrolled fields. By React's convention, functions that use async transitions are called . The article on controlled and uncontrolled inputs showed how to read the fields from FormData; this one is about the state around the submission.
useActionState keeps the result and the pending flag
useActionState(action, initialState) returns three things: the current state, a function to give to the form's action, and isPending, which is true while its actions run. Your action receives the previous state first and the FormData second, and whatever it returns becomes the new state. That's where expected errors go: the docs suggest returning validation messages as part of the state. Unexpected errors can simply be thrown: React cancels any queued actions and shows the nearest Error Boundary.
import { useState, type FormEvent } from "react";export function InviteForm() { const [email, setEmail] = useState(""); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState<string | null>(null); async function handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); setIsLoading(true); setError(null); const result = await sendInvite(email); // a throw skips the next lines setError(result.error ?? null); setIsLoading(false); } return ( <form onSubmit={handleSubmit}> <input value={email} onChange={(e) => setEmail(e.target.value)} /> <button disabled={isLoading}>{isLoading ? "Sending…" : "Invite"}</button> {error && <p role="alert">{error}</p>} </form> );}import { useActionState } from "react";type State = { error: string | null; email: string };async function invite(_prev: State, formData: FormData): Promise<State> { const email = String(formData.get("email")); const { error } = await sendInvite(email); return error ? { error, email } : { error: null, email: "" };}export function InviteForm() { const [state, formAction, isPending] = useActionState(invite, { error: null, email: "", }); return ( <form action={formAction}> <input name="email" defaultValue={state.email} /> <button disabled={isPending}>{isPending ? "Sending…" : "Invite"}</button> {state.error && <p role="alert">{state.error}</p>} </form> );}setIsLoading pair to break: isPending ends when the Transition does, so a timeout goes to the nearest Error Boundary instead of freezing the button. And the error message is just the latest returned state, so a successful retry replaces it. React also queues submissions and runs them one after another, each receiving the previous result, so a double click sends two invites in turn instead of racing them.
useFormStatus for buttons deep inside the form
isPending prop threaded into it. useFormStatus from react-dom returns the status of the form the component is rendered in:
import { useFormStatus } from "react-dom";// Disables itself inside any <form action>, no props neededexport function SubmitButton({ label }: { label: string }) { const { pending } = useFormStatus(); return <button disabled={pending}>{pending ? "Saving…" : label}</button>;}<form>. Called in the same component that renders the form, pending is never true, so it has to live in a child component like this one.
useOptimistic for instant feedback
useOptimistic(value) returns a value you can override inside an Action. The override shows while the Action is pending; when it ends, React renders the real value in the same render, and if the Action throws, the screen falls back to whatever the real value is.
onSubmit and useState | ||
|---|---|---|
e.preventDefault() every time | action | |
isLoading set around the await | isPending, or pending from useFormStatus | |
try/finally, or a stuck spinner | ||
How to apply it in your project
Find the plumbing Search for preventDefault()in submit handlers and forsetIsLoading(true)paired withsetIsLoading(false). Each pair is a candidate.Turn the handler into an action Write a function that takes the previous state and the FormData, calls your API and returns the next state, including any expected error. Pass it throughuseActionState.Move pending UI into the form's children Replace isLoadingwithisPending, and give shared submit buttonsuseFormStatusinstead of a prop.Decide what survives an error Return the submitted values with the error, or keep those fields controlled, and wrap the form in an Error Boundary for failures you didn't expect.
Key takeaways
A function passed to <form action>runs as an Action: it getsFormData, needs nopreventDefaultand runs in a Transition.useActionStateturns what the action returns into state and gives youisPending; no flags to set or forget.Return expected errors as state, throw unexpected ones to an Error Boundary, and give fields their values back on error. useFormStatusgives nested buttons the pending state;useOptimisticshows the result before the server confirms.
التعليقات (0)