Sub topic 2
Why `useFormStatus` Must Live in a Child of the Form
Assume you know React function components, hooks, JSX, HTML forms, FormData, and asynchronous functions. This chapter focuses on the component boundary that makes pending form UI work.
The child component rule
A form action is a function passed to a form’s action prop. React runs that function when the form submits. useFormStatus reads the status of the nearest parent form.
The component calling the hook must be rendered inside that form. A component that calls useFormStatus while also creating the form is outside the form from the hook’s point of view.
This arrangement lets a reusable button respond to any parent form without receiving pending as a prop.
'use client';
import { useFormStatus } from 'react-dom';
function SubmitButton({ children = 'Save', pendingLabel = 'Saving...' }) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending} aria-disabled={pending}>
{pending ? pendingLabel : children}
</button>
);
}
export default function ProfileForm() {
async function saveProfile(formData) {
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log('Saved', formData.get('name'));
}
return (
<form action={saveProfile}>
<input name="name" placeholder="Name" required />
<SubmitButton pendingLabel="Saving profile..." />
</form>
);
}Designing the pending state
A pending button should prevent duplicate submissions, explain the current state, and remain understandable to assistive technology.
- Use
disabled={pending}to prevent another click while the action runs. - Change the label from an action such as “Save” to progress text such as “Saving...”.
- A spinner can reinforce progress visually. Mark a decorative spinner with
aria-hidden="true". - Keep important progress text in the button label or expose it through an element with
role="status"andaria-live="polite".
Exercise
Why does pending stay false when useFormStatus is called in the component that returns the form?
Show answer
That component is not a child of the form it creates. Move the hook into a rendered child such as SubmitButton.