Sub topic 5
Building a reusable SubmitButton
This chapter assumes you know React function components, props, and hooks. It also assumes you know how useFormStatus reads the pending flag, and why the hook must be called from a child of the form rather than from the component that renders the form. Here you turn that hook into a component you can put in any form of an application.
Why a dedicated component
Every form needs the same behavior while it submits. The button should not accept a second click, and its label should show that work is happening. Writing that logic inline in each form has two costs:
- The logic is duplicated, so a fix has to be applied in every form.
- The inline version is often wrong. The component that renders
<form>cannot read that form's status, sopendingstaysfalsethere.
A SubmitButton component solves both. It is always rendered inside a form, so the child-of-the-form rule holds by construction. Forms use it like a normal button and do not need to know about the hook.
The first version
Start with the smallest useful component.
'use client';
import { useFormStatus } from 'react-dom';
export default function SubmitButton({ children }) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Saving...' : children}
</button>
);
}Three details matter:
'use client'is required if the file is used in a framework with Server Components. Hooks only run in Client Components.type="submit"is explicit. It is the default for a button in a form, but stating it makes the intent clear. It also protects the component if someone later wraps it somewhere unusual.- The hardcoded
'Saving...'is the weakness. A "Delete account" button should not say "Saving...". The next section fixes that.
Making the component configurable
A reusable component takes the parts that vary as props and fixes the parts that must not vary. For a submit button, these are the pieces that vary:
- The idle label, passed as
children. - The pending label, passed as
pendingLabelwith a neutral default. - Any other button attribute, such as
className,name,value, orform. - An extra reason to disable the button, such as invalid input.
These are the pieces that must not vary:
- The
pendingstate comes from the hook, never from props. - A pending button is always disabled.
'use client';
import { useFormStatus } from 'react-dom';
export default function SubmitButton({
children,
pendingLabel = 'Working...',
disabled = false,
...rest
}) {
const { pending } = useFormStatus();
return (
<button
{...rest}
type="submit"
disabled={pending || disabled}
aria-busy={pending}
>
{pending ? pendingLabel : children}
</button>
);
}The ...rest spread comes first, and type, disabled, and aria-busy come after it. In JSX, later props win. A caller who passes type="button" or disabled={false} by accident therefore cannot break the pending behavior. The component still honors the caller's disabled request through the pending || disabled expression.
aria-busy tells assistive technology that the element is updating. Support for it varies across screen readers, so treat it as a hint and not as the only signal. Chapter material on pending-state design covers accessibility in more depth. For now, the label change is the primary signal, because it is real text in the button.
Using it in two different forms
The same component serves unrelated forms. This example runs as written in a React 19 app.
'use client';
import SubmitButton from './SubmitButton';
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export default function Settings() {
async function saveProfile(formData) {
await wait(1000);
console.log('Saved', formData.get('name'));
}
async function deleteAccount() {
await wait(1500);
console.log('Deleted');
}
return (
<>
<form action={saveProfile}>
<input name="name" placeholder="Name" />
<SubmitButton pendingLabel="Saving...">Save</SubmitButton>
</form>
<form action={deleteAccount}>
<SubmitButton pendingLabel="Deleting..." className="danger">
Delete account
</SubmitButton>
</form>
</>
);
}Each SubmitButton sits inside its own <form>, so each reads the status of its own nearest parent form. Submitting the first form does not disable the second button. This is the main benefit of the hook's design. The status comes from the surrounding form, not from shared state that you have to wire up by hand.
Where the component lives
Put SubmitButton in its own file and import it wherever it is needed. This is the pattern that keeps it reusable, and it matters for one more reason: the file boundary is where 'use client' goes.
In a framework that supports Server Components, a form can stay in a Server Component while the button is the only Client Component. The form uses a Server Action as its action.
// actions.js
'use server';
export async function createPost(formData) {
const title = formData.get('title');
// Save the post to a database here.
}
// NewPostForm.jsx (a Server Component)
import { createPost } from './actions';
import SubmitButton from './SubmitButton';
export default function NewPostForm() {
return (
<form action={createPost}>
<input name="title" required />
<SubmitButton pendingLabel="Publishing...">Publish</SubmitButton>
</form>
);
}NewPostForm has no 'use client' directive and no hooks, so it ships no extra JavaScript for itself. Only the small button is a Client Component. The pending state still works because SubmitButton is rendered inside the <form> element.
The children and pendingLabel props here are plain strings, which a Server Component can pass to a Client Component without trouble. If you pass a function as a prop across that boundary, it must be a Server Action. Ordinary functions cannot be serialized.
Handling several buttons in one form
Some forms have more than one submit button, for example "Save draft" and "Publish". Both are children of the same form, so both read the same pending value. With the component as written, clicking either one disables both and changes both labels. That is often not what you want, because the user sees "Saving..." on a button they did not press.
The submitted data tells you which button was used. A button with a name and value adds that pair to the form's FormData, and useFormStatus exposes that FormData as data while the submission is pending. You can compare it to decide whether this button is the one in flight.
'use client';
import { useFormStatus } from 'react-dom';
export default function SubmitButton({
children,
pendingLabel = 'Working...',
name,
value,
disabled = false,
...rest
}) {
const { pending, data } = useFormStatus();
// This button is "active" if the form is pending and either
// this button has no name (so we cannot tell) or its pair was submitted.
const isSubmitter =
pending && (!name || data?.get(name) === value);
return (
<button
{...rest}
type="submit"
name={name}
value={value}
disabled={pending || disabled}
aria-busy={isSubmitter}
>
{isSubmitter ? pendingLabel : children}
</button>
);
}Use it like this:
<form action={savePost}>
<input name="title" />
<SubmitButton name="intent" value="draft" pendingLabel="Saving draft...">
Save draft
</SubmitButton>
<SubmitButton name="intent" value="publish" pendingLabel="Publishing...">
Publish
</SubmitButton>
</form>While the form is pending, both buttons are disabled, so the user cannot start a second submission. Only the button that was pressed changes its label. The action reads formData.get('intent') to learn what the user chose.
Disabled versus aria-disabled
Setting disabled is the simplest way to stop repeat clicks, and it has a useful side effect. Per the HTML specification, if a form's default submit button is disabled, pressing Enter in a text input does not submit the form either. One attribute therefore blocks both click and keyboard submission.
It has a drawback. A disabled button cannot be focused. If the user activated the button by keyboard, focus can drop to the page body when the button becomes disabled, and some screen readers then stop announcing what the user was doing. Some teams prefer aria-disabled="true", which keeps the button focusable and still announces it as unavailable.
If you choose aria-disabled, the browser no longer blocks anything for you. You must stop the submission in code:
'use client';
import { useFormStatus } from 'react-dom';
export default function SubmitButton({ children, pendingLabel = 'Working...', ...rest }) {
const { pending } = useFormStatus();
function handleClick(event) {
if (pending) event.preventDefault();
}
return (
<button
{...rest}
type="submit"
aria-disabled={pending}
onClick={handleClick}
>
{pending ? pendingLabel : children}
</button>
);
}preventDefault on the click stops the button from submitting. It does not stop Enter pressed inside a text input from submitting the form, because that goes through implicit submission, which still sees an enabled default button. To block that case too, guard inside the action function itself, or keep using disabled.
| Approach | Blocks click | Blocks Enter in an input | Keeps keyboard focus | Extra code |
|---|---|---|---|---|
| `disabled={pending}` | Yes | Yes | No | None |
| `aria-disabled` with `preventDefault` | Yes | No | Yes | Click handler, plus an action-side guard |
For most forms, disabled is the right default. Choose aria-disabled when keyboard focus continuity matters to your users, and accept the extra guard code that comes with it.
Style the pending state with attributes
Give styles something stable to hook onto instead of the label text. Reflecting state in an attribute lets CSS do the visual work, such as dimming the button or showing a spinner.
<button
{...rest}
type="submit"
disabled={pending || disabled}
aria-busy={pending}
data-pending={pending ? '' : undefined}
>
{pending ? pendingLabel : children}
</button>button[data-pending] {
opacity: 0.6;
cursor: progress;
}data-pending={pending ? '' : undefined} renders the attribute when pending and omits it entirely otherwise. Passing false to a data- attribute would render the string "false", which a selector like [data-pending] would still match. That is a common source of buttons that look permanently pending.
Checklist for a reusable button
Before you reuse the component across an application, check each of these:
- It is rendered inside a
<form>, never beside it. Rendering it outside givespending: falsealways. - The hook call is in
SubmitButtonand not in the component that renders the<form>. type="submit",disabled, and the pending label come after{...rest}so callers cannot override them.- The pending label is passed in from the form, so each form says something accurate.
- The file has
'use client'when used with Server Components. - The label changes in text, not only in color or an icon.
Testing the component
You can check the behavior without a browser by rendering a form with an action that you control and asserting on the button. This example uses React Testing Library and Vitest or Jest. Because the action is async, the test resolves it by hand.
import { render, screen, fireEvent, act } from '@testing-library/react';
import SubmitButton from './SubmitButton';
test('disables the button and shows the pending label while the action runs', async () => {
let finish;
const action = () => new Promise((resolve) => { finish = resolve; });
render(
<form action={action}>
<SubmitButton pendingLabel="Saving...">Save</SubmitButton>
</form>
);
const button = screen.getByRole('button');
expect(button).toHaveTextContent('Save');
await act(async () => {
fireEvent.click(button);
});
expect(button).toBeDisabled();
expect(button).toHaveTextContent('Saving...');
await act(async () => {
finish();
});
expect(button).toBeEnabled();
expect(button).toHaveTextContent('Save');
});The test controls when the promise settles. That makes the pending window long enough to observe, without arbitrary timeouts. The toBeDisabled and toHaveTextContent matchers come from @testing-library/jest-dom, which you need to have set up.
Summary
A reusable SubmitButton wraps one hook call and a few decisions: pending comes from useFormStatus, the labels come from props, and the button disables itself while the form submits. Spread extra props first so they cannot override the pending behavior. Choose disabled for the simplest reliable blocking, or aria-disabled if you need focus to stay on the button. For forms with several submit buttons, use name and value with the status data to mark only the pressed button.
Exercise
A teammate writes SubmitButton with <button disabled={pending} {...rest}> and a form passes disabled={false} to it through rest. The button then stays clickable during submission. What is the cause and the fix?
Show answer
The {...rest} spread comes after disabled={pending}, so the caller's disabled={false} overrides the pending value. Later props win in JSX. The fix is to put {...rest} first and set disabled={pending || disabled} after it, taking disabled out of rest as its own prop, so the button is disabled whenever the form is pending or the caller asks for it.
Exercise
A form has "Save draft" and "Publish" buttons built from the multi-button SubmitButton. Both show "Working..." when either is pressed, even though each has a name and a value. List two things to check.
Show answer
First, confirm the name and value props are actually passed to the underlying <button> element, because the FormData only contains the pressed button's pair if the button renders those attributes. Second, confirm the comparison matches exactly, for example data?.get(name) === value, and that the pending label depends on the computed isSubmitter value and not on pending alone.
Exercise
You switch SubmitButton from disabled to aria-disabled with a click handler that calls preventDefault while pending. Users report that pressing Enter in a text field still starts a second submission. Why does it happen, and what are two ways to prevent it?
Show answer
Pressing Enter in a text input triggers implicit submission through the form's default button. A button with only aria-disabled is still an enabled button to the browser, and preventDefault on its click handler is not involved in that path, so the form submits again. One fix is to return to disabled, which makes the browser skip implicit submission when the default button is disabled. The other is to guard inside the action function, for example by tracking an in-flight flag and returning early when a submission is already running.