React / 89
useActionState and useFormStatus
Let a form's async action return its next state, such as errors and results, with useActionState. Show a pending button anywhere inside the form with useFormStatus.
useActionState: a reducer that can await
const [state, formAction, isPending] = useActionState(addDish, { error: null })stateWhat your action returned last time. Starts as the initial state.
formActionPass it to <form action>, or call it inside startTransition.
isPendingtrue while any call to this action is still running.
async function addDish(prevState, formData) { // …await the save… return nextState // becomes `state`}import { useActionState } from "react";
import { useFormStatus } from "react-dom";
import { saveDish } from "./api.js";
async function addDish(prevState, formData) {
const name = formData.get("dish").trim();
if (!name) return { ...prevState, error: "Give the dish a name." };
await saveDish(name);
return { dishes: [...prevState.dishes, name], error: null };
}
function SubmitButton() {
const { pending } = useFormStatus();
return <button disabled={pending}>{pending ? "Adding…" : "Add dish"}</button>;
}
export default function AddDishForm() {
const initial = { dishes: [], error: null };
const [state, formAction] = useActionState(addDish, initial);
return (
<form action={formAction}>
<input name="dish" />
<SubmitButton />
{state.error && <p role="alert">{state.error}</p>}
<ul>{state.dishes.map((d) => <li key={d}>{d}</li>)}</ul>
</form>
);
}Three things to notice:
- The action takes
(prevState, formData). A plain form action takes onlyformData, so the arguments shift by one when you switch. - The returned value becomes
state. There's nosetStateafter theawait, so no extrastartTransitionis needed. initialStateis only used until the first submit. After that,stateis whatever the action last returned.
A form with useActionState
Try itstate.error is null
state.dishes
Masala dosa
Paneer tikka
isPending
useFormStatus: the pending state, for children
useFormStatus comes from react-dom and takes no arguments. It returns { pending, data, method, action } for the parent <form>. pending is true while the form's Action runs, and data is the FormData being sent, which is handy for showing "Adding Mango lassi…".
It works a bit like reading a Context that the form provides, which is why it only sees a form above the component that calls it:
works
<DishForm />
parent form
<form action={formAction}>
child component
<SubmitButton />
doesn't work
<DishForm />
pending is always false
This makes design-system buttons easy: one <SubmitButton /> works in every form without passing isPending down as a prop.
Calling it without a form
formAction doesn't need a <form>. Call it with any payload, but inside a transition, or React logs an error and isPending won't update:
function handleAdd() {
startTransition(() => formAction({ type: "ADD", dish: "Idli" }));
}Gotchas
Recall
Can you answer these?
0/5
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
