In the previous post, we compared three approaches to handling form submissions: plain onSubmit,
onSubmit with useTransition, and the action prop. In this post, we'll explore how useActionState works
with forms and compare it with using the action prop alone. Although useActionState isn't limited to forms,
we'll focus on form submissions here.
Background on useActionState
Basically, useActionState manages the result and pending status of a function you want to run.
This function can contain side effects, and React stores the value it returns.
Your component can use the pending status and returned value to show progress and display the result.
Let's look at the hook's basic usage:
const [state, dispatchAction, isPending] = useActionState(reducerAction, initialState);
reducerAction is the function we want to run. To run it, we call dispatchAction, which must be called inside a Transition. We can do this by calling it inside startTransition,
or by passing it to a form’s action prop, which starts the Transition automatically.
When we call dispatchAction(payload), React calls reducerAction(previousState, payload). On the first call, previousState is the initialState
we supplied to the hook; on subsequent calls, it's the value returned by the previous call to reducerAction. Whatever reducerAction returns becomes the hook's new state
represented by the state variable above.
Let's look at a basic example, passing reducerAction as an inline function:
import { startTransition, useActionState } from "react"; import { saveName } from "./api"; export default function NameForm() { const [state, dispatchAction, isPending] = useActionState<string, string>(async (previousState, payload) => { await saveName(payload); return `Saved ${payload}`; }, ""); return ( <> <button disabled={isPending} onClick={() => { startTransition(() => { dispatchAction("Alex"); }); }} > {isPending ? "Saving..." : "Save name"} </button> <p>{state}</p> </> ); }
Initially, state is an empty string. Clicking "Save name" calls dispatchAction("Alex"), so the function passed to the hook receives "" as
previousState and "Alex" as payload. While saveName runs, isPending is true, disabling the button and displaying "Saving...". Once
reducerAction returns, state becomes "Saved Alex", which appears below the button, and isPending becomes false. If we click the button again,
React will pass "Saved Alex" as previousState to reducerAction. But in this example, we don't use previousState inside reducerAction.
When you want to use useActionState with forms, you can pass the dispatchAction function to a form's action prop,
or call it yourself inside startTransition, for example from onSubmit.
Newsletter Form Example
Now let's build on the newsletter example from the previous post
and use it to compare two approaches: one using the action prop alone and one using useActionState together with action prop.
We'll also modify this example to validate the email as the user types.
As we saw earlier, useActionState exposes the state returned by the function passed to the hook
(state in our earlier example, the first value destructured from the hook's return),
and that state could include field validation errors too.
However, those errors would only become available after submission,
once that function finishes. Making users submit the form just to discover an invalid email
would be a poor user experience, so let's explore how to provide validation feedback while
typing too, while still using useActionState to handle the submission result.
Also this time, we'll use a controlled input.
The main reason is to prevent it from resetting automatically after submission,
as explained in the previous post's section on automatic form reset.
We could also keep the input uncontrolled and still display validation errors while typing by validating the value in onChange and storing any error in React state.
Both examples use the same mock API and email validation helper:
function validateEmail(email: string): string | null { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? null : "Enter a valid email."; } // Use test@example.com to simulate an already-subscribed email. async function subscribe(email: string) { await new Promise((resolve) => setTimeout(resolve, 1000)); if (email === "test@example.com") { return { success: false as const, error: "This email is already subscribed.", }; } return { success: true as const }; }
Both forms use noValidate to disable the browser's built-in submission validation so we can display our own validation messages.
Handling Form Submission with action Prop Alone
First, here's the version using the action prop alone:
import { startTransition, useState, type ChangeEvent } from "react"; import { useFormStatus } from "react-dom"; function SubmitButton() { const { pending } = useFormStatus(); return ( <button type="submit" disabled={pending}> {pending ? "Subscribing..." : "Subscribe"} </button> ); } function FormMessages({ error, success }: { error: string; success: boolean }) { const { pending } = useFormStatus(); if (pending) return null; return ( <> {error && <p role="alert">{error}</p>} {success && <p role="status">Successfully subscribed!</p>} </> ); } export default function NewsletterForm() { const [email, setEmail] = useState(""); const [emailFieldError, setEmailFieldError] = useState<string | null>(null); const [error, setError] = useState(""); const [success, setSuccess] = useState(false); function handleChange(event: ChangeEvent<HTMLInputElement>) { const value = event.currentTarget.value; setEmail(value); setEmailFieldError(validateEmail(value)); } async function action(formData: FormData) { setError(""); setSuccess(false); // Get the email from the form data and validate it. const value = formData.get("email"); const submittedEmail = typeof value === "string" ? value : ""; const validationError = validateEmail(submittedEmail); // Update the email field error state, then return early if the email is invalid. setEmailFieldError(validationError); if (validationError) return; try { const result = await subscribe(submittedEmail); if (!result.success) { startTransition(() => { setError(result.error); }); return; } startTransition(() => { setSuccess(true); }); } catch { startTransition(() => { setError("Something went wrong. Please try again."); }); } } return ( <form action={action} noValidate> <label htmlFor="email">Email</label> <input id="email" type="email" name="email" value={email} onChange={handleChange} placeholder="Enter your email" aria-invalid={Boolean(emailFieldError)} aria-describedby={emailFieldError ? "email-error" : undefined} /> {/* Email field error message */} {emailFieldError && ( <p id="email-error" role="alert"> {emailFieldError} </p> )} <SubmitButton /> <FormMessages error={error} success={success} /> </form> ); }
Handling Form Submission Using useActionState and action Prop
Below is an example of using useActionState with the action prop:
import { useActionState, useState, type ChangeEvent } from "react"; type SubmissionResult = { success: true } | { success: false; error: string }; export default function NewsletterForm() { const [email, setEmail] = useState(""); const [emailFieldError, setEmailFieldError] = useState<string | null>(null); const [result, dispatchAction, isPending] = useActionState<SubmissionResult | null, FormData>( async (_previousState, formData) => { // Get the email from the form data and validate it. const value = formData.get("email"); const submittedEmail = typeof value === "string" ? value : ""; const validationError = validateEmail(submittedEmail); // Update the email field error state, then return early if the email is invalid. setEmailFieldError(validationError); if (validationError) return null; try { return await subscribe(submittedEmail); } catch { return { success: false, error: "Something went wrong. Please try again.", }; } }, null, ); function handleChange(event: ChangeEvent<HTMLInputElement>) { const value = event.currentTarget.value; setEmail(value); setEmailFieldError(validateEmail(value)); } return ( <form action={dispatchAction} noValidate> <label htmlFor="email">Email</label> <input id="email" type="email" name="email" value={email} onChange={handleChange} placeholder="Enter your email" aria-invalid={Boolean(emailFieldError)} aria-describedby={emailFieldError ? "email-error" : undefined} /> {/* Email field error message */} {emailFieldError && ( <p id="email-error" role="alert"> {emailFieldError} </p> )} <button type="submit" disabled={isPending}> {isPending ? "Subscribing..." : "Subscribe"} </button> {!isPending && result?.success === false && <p role="alert">{result.error}</p>} {!isPending && result?.success === true && <p role="status">Successfully subscribed!</p>} </form> ); }
Comparing Both Approaches
Accessing Pending Status Directly
With useActionState, we have access to isPending directly in NewsletterForm. We no longer need separate SubmitButton and
FormMessages components just to read pending status through useFormStatus.
Managing the Submission Result
The useActionState hook also stores the submission result, exposed as result in our example, replacing the separate success and error state variables from the example using the action prop alone.
In both examples, submission messages describe the last submission and remain visible if the user continues typing after the messages appear.
With the action prop alone, we can simply clear the success and error state when we want to dismiss the previous submission messages.
With useActionState, we could make the function passed to the hook recognize a reset payload and return a new state with the result messages cleared. However, we
should keep in mind that this returned state becomes the previousState received by the next call to that function. Therefore, if we want to preserve
other information stored in the state, we should clear only the result messages rather than reset the entire state.
Another option with useActionState is a separate showResult flag. Set it to false to hide the previous message and back to true to show the result of a new submission. This hides the previous message
without modifying the hook's stored result or calling the function again just to clear it.
Updating State After await
In our example using the action prop alone, state updates after an await are not Transition updates, so we wrap them in an additional startTransition.
With useActionState, we return the result from the function passed to the hook instead of calling setters, so there's nothing to wrap.
But if we called a state setter after an await inside the function passed to useActionState, we’d still need to wrap that update in startTransition to make it a Transition update.
Queuing Multiple Calls to dispatchAction
useActionState queues multiple dispatches and runs them sequentially, passing
each call's returned state to the next call. Passing a function directly to the form's action prop without using useActionState does not provide this queue, so multiple submissions can run concurrently.
For example, suppose each call does some async work before incrementing a counter. With useActionState, three quick dispatches starting from
0 would calculate 1, then 2, then 3. With the action prop alone, three submissions made before that work finishes could all read the same count of 0 and each set it to 1.
In the version using the action prop alone, using setCount(previous => previous + 1) would fix the lost increments, but the async calls would still run concurrently.
Progressive Enhancement
In the previous post, we
mentioned that passing a React Server Function to a form's action prop allows the form to be submitted before JavaScript loads or even when it is disabled.
When we pass a Server Function to useActionState and use the returned dispatch function as the form's action prop, the form can still submit without JavaScript.
Unlike using the action prop alone, useActionState also lets the component display the state returned by the Server Function, even before JavaScript loads or when it is disabled.
See the React docs for an example of displaying a form submission error without JavaScript.
Here's a minimal version of our newsletter example for a framework that supports React Server Functions.
Assume subscribeAction is implemented in server-actions.ts as a React Server Function using 'use server'.
It accepts the previous state and FormData, runs our validation and subscription logic, and returns { success: true } or { success: false, error }.
"use client"; import { useActionState } from "react"; import { subscribeAction } from "./server-actions"; // This form works even without JavaScript. export default function NewsletterForm() { const [result, dispatchAction] = useActionState(subscribeAction, null); return ( <form action={dispatchAction} noValidate> <label htmlFor="email">Email</label> <input id="email" type="email" name="email" /> <button type="submit">Subscribe</button> {/* These result messages appear even without JavaScript. */} {result?.success === false && <p role="alert">{result.error}</p>} {result?.success === true && <p role="status">Successfully subscribed!</p>} </form> ); }
We could also add an onSubmit handler alongside action={dispatchAction}, which would run once JavaScript has loaded and the form is hydrated.
Inside it, we could call event.preventDefault() to stop the function passed to the action prop from running automatically,
then run our own logic, such as the field validation from our earlier example, before calling the dispatch function dispatchAction(formData) inside startTransition.
In that case, the form would still work without JavaScript, while client-side validation would add a richer experience when JavaScript is available.
Comparison Table
| Behavior |
|
|
|---|---|---|
| Read pending status | Read | Read |
| Store the submission result | Manage result state yourself | The hook stores the returned value as state |
| Hide submission messages when the user edits again | Clear the message state directly, e.g. call | Use a separate visibility flag, or dispatch a reset payload (which has trade-offs). See Managing the submission result |
Update state after await | Wrap updates in an additional | The new state can be returned from the function passed to the hook, so no additional |
| Handle multiple calls | Calls to the function passed to action can run concurrently | dispatchAction calls are queued and executed sequentially. The function passed to the hook receives the result of the previous call. |
| Submit without JavaScript using a React Server Function | Supported in a compatible framework | Supported in a compatible framework |
| Display the Server Function's returned state without JavaScript (in a compatible framework) | Not supported | Supported |