Sub topic 1
Form actions: passing a function to the form's action prop
Prerequisites
Assume you know React function components and hooks, JSX, props, HTML forms, FormData, and basic asynchronous functions.
Form actions
A form action is a function passed to the form’s action prop. When the user submits the form, React calls that function and passes a FormData object containing the named form fields.
The action can be asynchronous. React tracks its submission while the returned promise is pending.
'use client';
import { useFormStatus } from 'react-dom';
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Saving...' : 'Save'}
</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" />
<SubmitButton />
</form>
);
}The name attribute connects the input to the FormData entry. In this example, formData.get('name') returns the submitted name.
What `useFormStatus` does
useFormStatus is a React hook imported from react-dom. It reads the status of the nearest parent form. The hook does not submit the form itself. It lets components inside the form respond to that submission.
The hook returns fields such as:
pending, a Boolean that istruewhile the action is running.data, the submittedFormData, while a submission is pending.method, the form’s HTTP method.action, the action associated with the form.
The component calling the hook must be rendered inside the <form>. This is why SubmitButton is separate from ProfileForm.
flowchart TD
A[User submits form] --> B[React calls saveProfile]
B --> C[pending becomes true]
C --> D[SubmitButton shows Saving]
B --> E[Promise resolves]
E --> F[pending becomes false]
F --> G[SubmitButton shows Save]Reading the pending flag
Use pending to prevent duplicate submissions and give immediate feedback. A disabled button also communicates that the current submission is still being processed. Keep the label change so users can understand why the control is temporarily unavailable.
Exercise
Where should a component that calls useFormStatus be rendered?
Show answer
It must be rendered as a descendant of the form whose status it needs to read.