📝
React19で追加されたhooks触ってみた2(useFormStatus)
useFormStatus
直近の親のフォームに関するステータス情報を取得するために利用する。
このhooksを利用することで、form要素の子として作成したコンポーネント(ボタンなど)は、propsで、ステータスを受け取ることなく、親のformの状態を取得できる。
定義
const { pending, data, method, action } = useFormStatus();
返り値
pending
親の<form>のactionが実行中かどうかを表す値。
実行中=true/実行していない=false。
data
FormDataインターフェースを実装したオブジェクト。
親のform要素がactionを実行した際のデータを保持している。
親のform要素がactionを実行していないか、そもそも親にform要素がない場合は、nullになる。
method
get or postの何れかの文字列。
親のform要素がGETとPOSTメソッドどちらを使用しているかを表す。
action
親のform要素のactionに渡された関数への参照。
子要素側で、親のformのactionを実行できる。
以下の場合、nullになる。
- 親に
form要素がない。 - 親の
formのactionにstringの値を渡している。 - 親の
formのactionに何も渡していない
使用例
const SubmitButton = () => {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
送信
</button>
)
}
const Form = () => {
return (
<div>
<form action={action}>
<SubmitButton />
</form>
</div>
)
}
注意点
-
form要素の子要素のコンポーネントで使用する必要がある。 - 親の
form要素のステータス情報を取得するため、同じコンポーネントや子コンポーネント内でレンダーされたformのステータス情報は取得できない。
const SubmitButton = () => {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
送信
</button>
)
}
const Form = () => {
// ❌ form要素と同じ階層にあるため、useFormStatusでステータス情報を取得できない
const { pending } = useFormStatus();
return (
<div>
<form action={action}>
{/* ✅ 親にform要素があるため、親のformのステータス情報をuseFormStatusで取得できる */}
<SubmitButton />
</form>
{/* ❌ form要素の外部のため、useFormStatusでステータス情報を取得できない */}
<SubmitButton />
</div>
)
}
- フォームのネスト時は、最も近い親の
form要素のステータス情報を取得する
const Forms = () => {
return (
<form action={outerAction}>
<form action={innerAction}>
<StatusButton /> {/* 最も近い親のform要素のinnerActionのステータスを取得する */}
</form>
</form>
);
}
感想
フォームの送信ボタンなどを共通化したい場合などに便利なhooksだと感じた。
ただ、ほぼ使用することはないが、methodの値がpostになるケースが、form要素のmethod属性にPOSTを設定した時のみだった。
また、action属性とmethod属性を同時に設定すると、以下のようなエラー表示されるため、action属性のみを指定した場合に、POSTになるケースがわからなかった。
Cannot specify a encType or method for a form that specifies a function as the action.
React provides those automatically.
They will get overridden. Error Component Stack
参考
Discussion