Sub topic 3
Handling submission with handleSubmit
This chapter assumes you know React function components and hooks, TypeScript generics, the browser's form submit event, and async/await. You should also have used useForm and register. By the end you will know what handleSubmit does on each submit and which formState flags it updates. You will also know the mistakes that cause double submits and missing data.
What handleSubmit returns
handleSubmit does not submit anything itself. You call it with your callback, and it returns a new event handler. You pass that handler to the form's onSubmit prop.
<form onSubmit={handleSubmit(onValid, onInvalid)}>Both arguments are functions, and only the first is required:
onValid(data, event)runs when validation passes.dataholds the form values.onInvalid(errors, event)runs when validation fails.errorshas the same shape asformState.errors.
The returned handler does these steps, in order:
- It calls
event.preventDefault(), so the browser does not reload the page. You never write this call yourself. - It sets
isSubmittingtotrue. - It validates every registered field.
- If validation passes, it awaits
onValid. If validation fails, it stores the errors, focuses the first invalid field, and callsonInvalidif you passed one. - It sets
isSubmittingback tofalseand updatesisSubmitted,isSubmitSuccessful, andsubmitCount.
A complete example
This form simulates a slow request. It uses built-in register rules, so it needs no schema yet. Zod arrives in a later chapter.
import {
useForm,
type SubmitHandler,
type SubmitErrorHandler,
} from "react-hook-form";
type ContactValues = {
name: string;
message: string;
};
export function ContactForm() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting, isSubmitSuccessful, submitCount },
} = useForm<ContactValues>({
defaultValues: { name: "", message: "" },
});
const onValid: SubmitHandler<ContactValues> = async (values) => {
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log("Sent", values);
};
const onInvalid: SubmitErrorHandler<ContactValues> = (fieldErrors) => {
console.log("Fields with errors:", Object.keys(fieldErrors));
};
return (
<form onSubmit={handleSubmit(onValid, onInvalid)} noValidate>
<label htmlFor="name">Name</label>
<input id="name" {...register("name", { required: "Name is required" })} />
{errors.name && <p role="alert">{errors.name.message}</p>}
<label htmlFor="message">Message</label>
<textarea
id="message"
{...register("message", {
required: "Message is required",
minLength: { value: 10, message: "Write at least 10 characters" },
})}
/>
{errors.message && <p role="alert">{errors.message.message}</p>}
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Sending..." : "Send"}
</button>
{isSubmitSuccessful && <p>Thanks, your message was sent.</p>}
<p>Attempts: {submitCount}</p>
</form>
);
}SubmitHandler<T> and SubmitErrorHandler<T> are the library's types for the two callbacks. Typing the callbacks gives you checked values and fieldErrors without repeating the shape.
Submission state in formState
handleSubmit writes to these formState fields. Reading a field subscribes the component to it, so the component re-renders only when a field you read changes.
| Field | Meaning |
|---|---|
| `isSubmitting` | `true` from the start of validation until `onValid` settles. |
| `isSubmitted` | `true` after the first submit, whether or not it passed validation. |
| `isSubmitSuccessful` | `true` if the last submit passed validation and `onValid` did not throw. |
| `submitCount` | Number of times the form was submitted, including failed attempts. |
isSubmitting only covers the full request if onValid returns a promise. If you write onValid as a plain function that starts a fetch without returning or awaiting it, isSubmitting goes back to false almost at once, and the button is no longer disabled.
Common mistakes
Passing handleSubmit without calling it
onSubmit={handleSubmit} is wrong. handleSubmit is a factory, so React would call it with the event, and it would return a function that nothing calls. The correct form is onSubmit={handleSubmit(onValid)}.
Submitting from outside the form
A button that is not inside the <form> cannot trigger submit. Call the returned handler yourself:
<button type="button" onClick={handleSubmit(onValid)}>
Save
</button>In this case there is no <form> event, so event may be undefined. Also give such buttons type="button". Inside a form, a button without a type defaults to submit and can submit the form by accident.
Expecting every value in data
data contains values from registered inputs only. A value set with defaultValues but never registered is not submitted, unless you read it with getValues. An input registered with disabled: true gives undefined. A native disabled attribute on the element has a similar effect, because the library does not read a disabled input's value. If a field must be sent but not edited, use readOnly instead.
Errors thrown in onValid
If onValid throws or its promise rejects, isSubmitting still returns to false and isSubmitSuccessful is false. Recent 7.x releases then rethrow the error from the returned handler. In React, an event handler error is not caught by an error boundary, so it can surface as an unhandled promise rejection. Catch expected failures inside onValid:
const onValid: SubmitHandler<ContactValues> = async (values) => {
try {
const response = await fetch("/api/contact", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
} catch (error) {
console.error(error);
}
};Showing a failure to the user, such as a server rejection on one field, uses setError. A later chapter covers it.
Controlling focus and the second argument
On a failed submit the library focuses the first field with an error. It uses the order in which fields were registered, which is usually the order they appear in the DOM. You can turn this off with shouldFocusError: false in useForm.
The second argument, onInvalid, is good for things the field messages cannot do. Examples are scrolling to a summary at the top of the page, logging an analytics event, or showing a toast saying that some fields need attention. It is optional. Without it, a failed submit shows messages and focuses the first bad field.
Reading the event
Both callbacks receive the original event as their last argument. This lets you tell which button submitted a form that has several actions:
const onValid = (values: ContactValues, event?: React.BaseSyntheticEvent) => {
const submitter = (event?.nativeEvent as SubmitEvent | undefined)?.submitter;
console.log(values, submitter?.getAttribute("name"));
};Give each button a name, such as name="draft" or name="publish", and branch on it. Use this sparingly. Two separate handleSubmit calls on two type="button" buttons are often clearer.
Exercise
A teammate writes const onSubmit = (values) => { fetch("/api/save", { method: "POST", body: JSON.stringify(values) }); };. The Save button uses disabled={isSubmitting}, but users can still click it twice and send two requests. Why, and what is the fix?
Show answer
onSubmit returns nothing, so handleSubmit has no promise to wait for. isSubmitting turns false as soon as the function returns, long before the request finishes. The fix is to make the callback async and await the fetch, or to return the promise. Then isSubmitting stays true until the request settles, and the button stays disabled.
Exercise
You add a "Save draft" button inside the form that should skip the validation of required fields, and a "Publish" button that should validate them. Name one way to do this with the tools from this chapter.
Show answer
Give both buttons type="button" and attach separate handlers. "Publish" uses onClick={handleSubmit(onPublish)}, which validates. "Save draft" uses onClick={() => onSaveDraft(getValues())}, which reads the current values without running validation. Alternatively, use one submit handler and read event.nativeEvent.submitter to branch, but then validation still runs for both buttons.