React Hook Form Async Validation
Wire async validators into React Hook Form, debounce server checks, and resolve field errors without blocking the submit button.
On this page
Introduction
This guide covers asynchronous validation with React Hook Form, a recurring concern in the form-validation scenario. Some rules cannot run in the browser: a username taken check, a coupon lookup, an address verification call. React Hook Form supports async validators, but a naive wire-up fires on every keystroke and races the submit. The fix is debounce plus a controller that cancels stale checks.
Register an async validator
Pass a function returning a promise to the validate option; a resolved true means valid, a string means an error message, and the form waits before marking the field valid.
The trade-off worth naming is that pass a function returning a promise to the validate option; a resolved true means valid, a string means an error message, and the form waits before marking the field valid adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
const { register, handleSubmit } = useForm({ mode: 'onBlur' });
register('username', {
validate: async (v) => {
const ok = await fetch('/api/check-username?u=' + encodeURIComponent(v)).then(r => r.ok);
return ok || 'Username already taken';
},
});
Debounce the check
Wrap the call in a debounce so the server is hit once after the user stops typing for 300 ms, not on every keystroke, which cuts load and removes flicker.
The trade-off worth naming is that wrap the call in a debounce so the server is hit once after the user stops typing for 300 ms, not on every keystroke, which cuts load and removes flicker adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
function debounce<T extends (...a: any[]) => any>(fn: T, ms: number) {
let t: ReturnType<typeof setTimeout>;
return (...a: Parameters<T>) => new Promise<ReturnType<T>>((res) => {
clearTimeout(t);
t = setTimeout(() => res(fn(...a) as ReturnType<T>), ms);
});
}
Cancel stale promises
Abort the previous request when a new keystroke arrives so a slow earlier response cannot overwrite a fresh field error, which is the classic race in async validation.
The trade-off worth naming is that abort the previous request when a new keystroke arrives so a slow earlier response cannot overwrite a fresh field error, which is the classic race in async validation adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
let ctrl: AbortController | null = null;
const check = async (v: string) => {
ctrl?.abort();
ctrl = new AbortController();
const r = await fetch('/api/check?u=' + v, { signal: ctrl.signal });
return r.ok || 'taken';
};
Keep submit responsive
Do not disable submit while async validators run; instead let the form track isSubmitting and reject handleSubmit if any field is invalid, so the user can click early without a dead UI.
The trade-off worth naming is that do not disable submit while async validators run; instead let the form track issubmitting and reject handlesubmit if any field is invalid, so the user can click early without a dead ui adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Surface server errors
If the server returns a 429 or 500, treat it as a transient field error with a retry hint rather than a hard invalid, so a flaky check does not lock the user out of the form.
The trade-off worth naming is that if the server returns a 429 or 500, treat it as a transient field error with a retry hint rather than a hard invalid, so a flaky check does not lock the user out of the form adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Test the race
Fire two checks in quick succession and assert the second result wins, then assert a valid value resolves to true and a taken value resolves to the message, so the async contract is pinned.
The trade-off worth naming is that fire two checks in quick succession and assert the second result wins, then assert a valid value resolves to true and a taken value resolves to the message, so the async contract is pinned adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Sources
Sources: React Hook Form docs, AbortController MDN.
FAQ
- Why does my async validator run on every keystroke?
- Set mode: "onBlur" or debounce the validate function; otherwise React Hook Form calls it on each change, which hammers the server and races earlier promises.
- How do I cancel a stale check?
- Create an AbortController per invocation, abort the previous one when a new validate starts, and ignore a rejected promise whose abort signal is set.
Report a problem with this articleOpens a pre-filled issue on GitHub.