← Hooked.
useActionState
公式ドキュメント ↗const [state, formAction, isPending] = useActionState(submitAction, initialState);
<form action={formAction}>
<input name="name" />
<button disabled={isPending}>{isPending ? "送信中…" : "送信"}</button>
</form>;
{
state.error && <p>{state.error}</p>;
}自分で組み立てるとどうなるか
// useActionStateを使わない場合
const [error, setError] = useState(null);
const [success, setSuccess] = useState(false);
const [isPending, startTransition] = useTransition();
function handleSubmit(e) {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const name = String(formData.get("name") ?? "").trim();
startTransition(async () => {
await new Promise((r) => setTimeout(r, 800));
if (name.length < 2) {
setError("2文字以上入力してください");
setSuccess(false);
return;
}
setError(null);
setSuccess(true);
});
}「送信中かどうか」「結果」「入力内容の取得」といった、毎回書きがちな定型コードをuseActionStateが代わりにやってくれる。
注意点
このデモは擬似的なaction(実際のサーバー通信はしていない)。Next.jsのServer Actions(サーバー側だけで動く“use server”関数)と組み合わせると、JavaScriptが無効な環境でもフォーム送信が動くようになる(プログレッシブエンハンスメント)。Hooked.は独立したクライアント側だけのデモページなので、ここではローカルの疑似関数で見た目の動きだけを再現している。