Accessibility (A11y)
React Hook Form has support for native form validation, which allows you to validate inputs with your own rules. Since most of us have to build forms with custom designs and layouts, it is our responsibility to make sure those are accessible (A11y).
The following code example works as intended for validation; however, it can be improved for accessibility.
import { useForm } from "react-hook-form"export default function App() {const {register,handleSubmit,formState: { errors },} = useForm()const onSubmit = (data) => console.log(data)return (<form onSubmit={handleSubmit(onSubmit)}><label htmlFor="name">Name</label><inputid="name"{...register("name", { required: true, maxLength: 30 })}/>{errors.name && errors.name.type === "required" && (<span>This is required</span>)}{errors.name && errors.name.type === "maxLength" && (<span>Max length exceeded</span>)}<input type="submit" /></form>)}
The following code example is an improved version by leveraging ARIA.
import { useForm } from "react-hook-form"export default function App() {const {register,handleSubmit,formState: { errors },} = useForm()const onSubmit = (data) => console.log(data)return (<form onSubmit={handleSubmit(onSubmit)}><label htmlFor="name">Name</label>{/* use aria-invalid to indicate that the field contains an error */}<inputid="name"aria-invalid={errors.name ? "true" : "false"}{...register("name", { required: true, maxLength: 30 })}/>{/* use role="alert" to announce the error message */}{errors.name && errors.name.type === "required" && (<span role="alert">This is required</span>)}{errors.name && errors.name.type === "maxLength" && (<span role="alert">Max length exceeded</span>)}<input type="submit" /></form>)}
After this improvement, the screen reader will say: “Name, edit, invalid entry, This is required.”
Wizard Form / Funnel
It's pretty common to collect user information through different pages and sections. We recommend using a state management library to store user input through different pages or sections. In this example, we are going to use little state machine as our state management library (you can replace it with redux if you are more familiar with it).
Step 1: Set up your routes and store.
import { BrowserRouter, Routes, Route } from "react-router-dom"import { createStore } from "little-state-machine"import Step1 from "./Step1"import Step2 from "./Step2"import Result from "./Result"createStore({data: {firstName: "",lastName: "",},})export default function App() {return (<BrowserRouter><Routes><Route path="/" element={<Step1 />} /><Route path="/step2" element={<Step2 />} /><Route path="/result" element={<Result />} /></Routes></BrowserRouter>)}
Step 2: Create your pages, collect and submit the data to the store and push to the next form/page.
import { useForm } from "react-hook-form"import { useNavigate } from "react-router-dom"import { useStateMachine } from "little-state-machine"import updateAction from "./updateAction"export default function Step1() {const { register, handleSubmit } = useForm()const { actions } = useStateMachine({ actions: { updateAction } })const navigate = useNavigate()const onSubmit = (data) => {actions.updateAction(data)navigate("/step2")}return (<form onSubmit={handleSubmit(onSubmit)}><input {...register("firstName")} /><input {...register("lastName")} /><input type="submit" /></form>)}
Step 3: Make your final submission with all the data in the store or display the resulting data.
import { useStateMachine } from "little-state-machine"export default function Result() {const { state } = useStateMachine()return <pre>{JSON.stringify(state, null, 2)}</pre>}
Following the above pattern, you should be able to build a wizard form/funnel to collect user input data from multiple pages.
Smart Form Component
The idea here is that you can easily compose your form using input components. We are going to create a Form component to automatically collect form data.
import { Form, Input, Select } from "./Components"export default function App() {const onSubmit = (data) => console.log(data)return (<Form onSubmit={onSubmit}><Input name="firstName" /><Input name="lastName" /><Select name="gender" options={["female", "male", "other"]} />{/* not routed through the custom Input — it has no `name`, so `Form` won't inject `register` for it */}<input type="submit" value="Submit" /></Form>)}
Let's have a look at what is inside each of these components.
</> Form
The Form component's responsibility is to inject all react-hook-form methods into the child component.
import { Children, createElement } from "react"import { useForm } from "react-hook-form"export default function Form({ defaultValues, children, onSubmit }) {const methods = useForm({ defaultValues })const { handleSubmit } = methodsreturn (<form onSubmit={handleSubmit(onSubmit)}>{Children.map(children, (child) => {return child.props.name? createElement(child.type, {...{...child.props,register: methods.register,key: child.props.name,},}): child})}</form>)}
</> Input / Select
The responsibility of these input components is to register themselves with react-hook-form.
export function Input({ register, name, ...rest }) {return <input {...register(name)} {...rest} />}export function Select({ register, options, name, ...rest }) {return (<select {...register(name)} {...rest}>{options.map((value) => (<option key={value} value={value}>{value}</option>))}</select>)}
With the Form component injecting react-hook-form's props into the child component, you can easily create and compose complex forms in your app.
Error Messages
Error messages are visual feedback to our users when there are issues with their inputs. React Hook Form provides an errors object to let you retrieve errors easily. There are several different ways to improve error presentation on the screen.
-
Register
You can simply pass the error message to
register, via themessageattribute of the validation rule object, like this:<input {...register('test', { maxLength: { value: 2, message: "error message" } })} /> -
Optional Chaining
The
?.optional chaining operator permits reading theerrorsobject without worrying about causing another error due tonullorundefined.errors?.firstName?.message -
Lodash
getIf your project is using lodash, then you can leverage the lodash get function. Eg:
get(errors, 'firstName.message')
Connect Form
When we are building forms, there are times when our input lives inside deeply nested component trees; that's when FormContext comes in handy. However, we can further improve the developer experience by creating a ConnectForm component and leveraging React's renderProps. The benefit is that you can connect your inputs to React Hook Form much more easily.
import { FormProvider, useForm, useFormContext } from "react-hook-form"export const ConnectForm = ({ children }) => {const methods = useFormContext()return children(methods)}export const DeepNest = () => (<ConnectForm>{({ register }) => <input {...register("deepNestedInput")} />}</ConnectForm>)export const App = () => {const methods = useForm()return (<FormProvider {...methods}><form><DeepNest /></form></FormProvider>)}
FormProvider Performance
React Hook Form's FormProvider is built upon React's Context API. It solves the problem where data is passed through the component tree without having to pass props down manually at every level. This also causes the component tree to trigger a re-render when React Hook Form triggers a state update; however, you can still optimize your application if required, as shown in the example below.
Note: Using React Hook Form's Devtools alongside FormProvider can cause performance issues in some situations. Before diving deep in performance optimizations, consider this bottleneck first.
import { memo } from "react"import { useForm, FormProvider, useFormContext } from "react-hook-form"// we can use memo to prevent re-renders except when the isDirty state changesconst NestedInput = memo(({ register, formState: { isDirty } }) => (<div><input {...register("test")} />{isDirty && <p>This field is dirty</p>}</div>),(prevProps, nextProps) =>prevProps.formState.isDirty === nextProps.formState.isDirty)export const NestedInputContainer = ({ children }) => {const methods = useFormContext()return <NestedInput {...methods} />}export default function App() {const methods = useForm()const onSubmit = (data) => console.log(data)console.log(methods.formState.isDirty) // make sure `formState` is read before rendering to enable the Proxyreturn (<FormProvider {...methods}><form onSubmit={methods.handleSubmit(onSubmit)}><NestedInputContainer /><input type="submit" /></form></FormProvider>)}
Controlled mixed with Uncontrolled Components
React Hook Form embraces uncontrolled components but is also compatible with controlled components. Some components in UI libraries like MUI and Antd (e.g. Select, Checkbox) do not expose a native input ref and must be wrapped with Controller. Simpler components like Input forward the ref and can be used directly with {...register}. React Hook Form also optimizes re-rendering for controlled components. Here is an example that combines both patterns with validation.
import { Input, Select, MenuItem } from "@mui/material"import { useForm, Controller } from "react-hook-form"const defaultValues = {select: 10,input: "",}function App() {const { handleSubmit, reset, control, register } = useForm({defaultValues,})const onSubmit = (data) => console.log(data)return (<form onSubmit={handleSubmit(onSubmit)}>{/* Controller's own defaultValue is ignored here — useForm's defaultValues takes precedence for the same field */}<Controllerrender={({ field }) => (<Select {...field}><MenuItem value={10}>Ten</MenuItem><MenuItem value={20}>Twenty</MenuItem></Select>)}control={control}name="select"/><Input {...register("input")} /><button type="button" onClick={() => reset({ ...defaultValues })}>Reset</button><input type="submit" /></form>)}
Custom Hook with Resolver
You can build a custom hook as a resolver. A custom hook can easily integrate with Yup/Joi/Superstruct as a validation method to be used inside a validation resolver.
- Define a memoized validation schema (or define it outside your component if you don't have any dependencies)
- Use the custom hook, by passing the validation schema
- Pass the validation resolver to the useForm hook
import { useCallback } from "react"import { useForm } from "react-hook-form"import * as yup from "yup"const useYupValidationResolver = (validationSchema) =>useCallback(async (data) => {try {const values = await validationSchema.validate(data, {abortEarly: false,})return {values,errors: {},}} catch (errors) {return {values: {},errors: errors.inner.reduce((allErrors, currentError) => ({...allErrors,[currentError.path]: {type: currentError.type ?? "validation",message: currentError.message,},}),{}),}}},[validationSchema])const validationSchema = yup.object({firstName: yup.string().required("Required"),lastName: yup.string().required("Required"),})export default function App() {const resolver = useYupValidationResolver(validationSchema)const { handleSubmit, register } = useForm({ resolver })return (<form onSubmit={handleSubmit((data) => console.log(data))}><input {...register("firstName")} /><input {...register("lastName")} /><input type="submit" /></form>)}
Working with virtualized lists
Imagine a scenario where you have a table of data. This table might contain hundreds or thousands of rows, and each row will have inputs. A common practice is to only render the items in the viewport; however, this causes issues as items are removed from the DOM when they are out of view and then re-added. This will cause items to reset to their default values when they re-enter the viewport.
An example is shown below using react-window.
import { memo } from "react"import { FormProvider, useForm, useFormContext } from "react-hook-form"import { VariableSizeList as List } from "react-window"import AutoSizer from "react-virtualized-auto-sizer"const items = Array.from(Array(1000).keys()).map((i) => ({title: `List ${i}`,quantity: Math.floor(Math.random() * 10),}))const WindowedRow = memo(({ index, style, data }) => {const { register } = useFormContext()return (<div style={style}><label>{data[index].title}</label><input {...register(`${index}.quantity`)} /></div>)})export const App = () => {const onSubmit = (data) => console.log(data)const methods = useForm({ defaultValues: items })return (<form onSubmit={methods.handleSubmit(onSubmit)}><FormProvider {...methods}><AutoSizer>{({ height, width }) => (<Listheight={height}itemCount={items.length}itemSize={() => 100}width={width}itemData={items}>{WindowedRow}</List>)}</AutoSizer></FormProvider><button type="submit">Submit</button></form>)}
Testing Form
Testing is important because it prevents bugs and mistakes. It also ensures code safety when refactoring.
We recommend using testing-library, because it is simple and tests are more focused on user behavior.
Step 1: Set up your testing environment.
Please install @testing-library/jest-dom with the latest version of jest, because react-hook-form uses MutationObserver to detect inputs, and to get unmounted from the DOM.
Note: If you are using React Native, you don't need to install @testing-library/jest-dom.
npm install -D @testing-library/jest-dom
Create setup.js to import @testing-library/jest-dom.
import "@testing-library/jest-dom"
Note: If you are using React Native, you need to create setup.js, define window object, and include the following lines in the setup file:
global.window = {}global.window = global
Finally, you have to update setup.js in jest.config.js to include the file.
module.exports = {setupFilesAfterEnv: ["<rootDir>/setup.js"], // or .ts for TypeScript App// ...other settings}
Additionally, you can set up eslint-plugin-testing-library and eslint-plugin-jest-dom to follow best practices and anticipate common mistakes when writing your tests.
Step 2: Create login form.
We have set the role attribute accordingly. These attributes are helpful when writing tests and improving accessibility. For more information, you can refer to the testing-library documentation.
import { useForm } from "react-hook-form"export default function App({ login }) {const {register,handleSubmit,formState: { errors },reset,} = useForm()const onSubmit = async (data) => {await login(data.email, data.password)reset()}return (<form onSubmit={handleSubmit(onSubmit)}><label htmlFor="email">email</label><inputid="email"{...register("email", {required: "required",pattern: {value: /\S+@\S+\.\S+/,message: "Entered value does not match email format",},})}type="email"/>{errors.email && <span role="alert">{errors.email.message}</span>}<label htmlFor="password">password</label><inputid="password"{...register("password", {required: "required",minLength: {value: 5,message: "min length is 5",},})}type="password"/>{errors.password && <span role="alert">{errors.password.message}</span>}<button type="submit">SUBMIT</button></form>)}
Step 3: Write tests.
The following criteria are what we aim to cover with the tests:
-
Test submission failure.
We are using
waitForutil andfind*queries to detect submission feedback, because thehandleSubmitmethod is executed asynchronously. -
Test validation associated with each input.
We are using the
*ByRolemethod when querying different elements because that's how users recognize your UI component. -
Test successful submission.
import { render, screen, fireEvent, waitFor } from "@testing-library/react"import App from "./App"const mockLogin = jest.fn((email, password) => {return Promise.resolve({ email, password })})it("should display required error when value is invalid", async () => {render(<App login={mockLogin} />)fireEvent.submit(screen.getByRole("button"))expect(await screen.findAllByRole("alert")).toHaveLength(2)expect(mockLogin).not.toBeCalled()})it("should display matching error when email is invalid", async () => {render(<App login={mockLogin} />)fireEvent.input(screen.getByRole("textbox", { name: /email/i }), {target: {value: "test",},})fireEvent.input(screen.getByLabelText("password"), {target: {value: "password",},})fireEvent.submit(screen.getByRole("button"))expect(await screen.findAllByRole("alert")).toHaveLength(1)expect(mockLogin).not.toBeCalled()expect(screen.getByRole("textbox", { name: /email/i })).toHaveValue("test")expect(screen.getByLabelText("password")).toHaveValue("password")})it("should display min length error when password is invalid", async () => {render(<App login={mockLogin} />)fireEvent.input(screen.getByRole("textbox", { name: /email/i }), {target: {value: "test@mail.com",},})fireEvent.input(screen.getByLabelText("password"), {target: {value: "pass",},})fireEvent.submit(screen.getByRole("button"))expect(await screen.findAllByRole("alert")).toHaveLength(1)expect(mockLogin).not.toBeCalled()expect(screen.getByRole("textbox", { name: /email/i })).toHaveValue("test@mail.com")expect(screen.getByLabelText("password")).toHaveValue("pass")})it("should not display error when value is valid", async () => {render(<App login={mockLogin} />)fireEvent.input(screen.getByRole("textbox", { name: /email/i }), {target: {value: "test@mail.com",},})fireEvent.input(screen.getByLabelText("password"), {target: {value: "password",},})fireEvent.submit(screen.getByRole("button"))await waitFor(() => {expect(screen.queryAllByRole("alert")).toHaveLength(0)// reset() fires after the async login resolves and triggers a re-render;// all post-reset assertions must be inside waitFor so they retry until// the DOM reflects the new state.expect(screen.getByRole("textbox", { name: /email/i })).toHaveValue("")expect(screen.getByLabelText("password")).toHaveValue("")})expect(mockLogin).toBeCalledWith("test@mail.com", "password")})
Resolving act warning during test
If you test a component that uses react-hook-form, you might run into a warning like this, even if you didn't write any asynchronous code for that component:
Warning: An update to MyComponent inside a test was not wrapped in act(...)
import { useForm } from "react-hook-form"export default function App() {const { register, handleSubmit } = useForm({mode: "onChange",})const onSubmit = (data) => {}return (<form onSubmit={handleSubmit(onSubmit)}><input{...register("answer", {required: true,})}/><button type="submit">SUBMIT</button></form>)}
import { render, screen } from "@testing-library/react"import App from "./App"it("should have a submit button", () => {render(<App />)expect(screen.getByText("SUBMIT")).toBeInTheDocument()})
In this example, there is a simple form without any apparent async code, and the test merely renders the component and checks for the presence of a button. However, it still logs the warning about updates not being wrapped in act().
This is because react-hook-form internally uses asynchronous validation handlers. In order to compute the formState, it has to initially validate the form, which is done asynchronously and results in another render. That update happens after the test function returns, which triggers the warning.
To solve this, wait until some element from your UI appears with find* queries. Note that you must not wrap your render() calls in act(). You can read more about wrapping things in act unnecessarily here.
import { render, screen } from "@testing-library/react"import App from "./App"it("should have a submit button", async () => {render(<App />)expect(await screen.findByText("SUBMIT")).toBeInTheDocument()// Now that the UI was awaited until the async behavior was complete,// you can keep asserting with `get*` queries.expect(screen.getByRole("textbox")).toBeInTheDocument()})
Transform and Parse
Native inputs return values in string format unless valueAsNumber or valueAsDate is used; you can read more in this section. However, it's not perfect, as we still have to deal with NaN or null values. Therefore, it's better to handle transformations at the custom hook level. In the following example, we use the Controller to handle input and output transformations. You can also achieve a similar result with a custom register.
Important: spread field onto the input before overriding onChange/value, so onBlur, name, and ref are still forwarded — without ref, RHF can't focus the input on a validation error, and without onBlur, isTouched never updates.
import { Controller } from "react-hook-form"const ControllerPlus = ({ control, transform, name, defaultValue }) => (<ControllerdefaultValue={defaultValue}control={control}name={name}render={({ field }) => (<input{...field}onChange={(e) => field.onChange(transform.output(e))}value={transform.input(field.value)}/>)}/>)// usage below:<ControllerPlustransform={{input: (value) => (isNaN(value) || value === 0 ? "" : value.toString()),output: (e) => {const output = parseInt(e.target.value, 10)return isNaN(output) ? 0 : output},}}control={control}name="number"defaultValue=""/>
Server Actions / useActionState
Next.js Server Actions and React's useActionState work well together, but combining them with React Hook Form can look convoluted if you try to sync state between them with useEffect. You don't need to: useActionState returns a plain dispatch function, so you can call it directly inside handleSubmit, and only after client-side validation has passed.
actions.js: a Server Action that receives the previous state and the validated form data.
"use server"export async function updateProfile(previousState, data) {try {await db.user.update({ data })return { success: true }} catch {return { success: false, error: "Something went wrong. Please try again." }}}
profile-form.jsx: handleSubmit runs validation first, then calls the action dispatcher (submitAction) with the already-parsed data, so there is no need to re-parse FormData on the server or bridge state with useEffect.
"use client"import { useForm } from "react-hook-form"import { useActionState } from "react"import { updateProfile } from "./actions"export default function ProfileForm() {const [state, submitAction, isPending] = useActionState(updateProfile, null)const {register,handleSubmit,formState: { errors },} = useForm()return (<form onSubmit={handleSubmit((data) => submitAction(data))}><input {...register("name", { required: "Name is required" })} />{errors.name && <span role="alert">{errors.name.message}</span>}<button type="submit" disabled={isPending}>{isPending ? "Saving..." : "Save"}</button>{state?.success && <p>Profile updated.</p>}{state?.error && <p role="alert">{state.error}</p>}</form>)}
isPending and state come straight from useActionState and are read directly in the JSX above, so there's nothing to synchronize: isPending replaces a manual loading useState, and state.success / state.error replace a manual result useState. The Server Action only runs once handleSubmit has confirmed the form is valid.
If the server needs to report field-level errors (for example, "email already in use"), map them onto React Hook Form's error state with setError. This is a legitimate use of useEffect, since you are synchronizing an external state source (the action's returned state) into the form rather than working around missing render-time state:
useEffect(() => {if (state?.fieldErrors) {for (const [name, message] of Object.entries(state.fieldErrors)) {setError(name, { type: "server", message })}}}, [state, setError])
If you don't need useActionState's pending/result state at all, React Hook Form's own Form component can submit directly to a Server Action through its action prop, with progressive enhancement handled for you.
Thank you for your support
If you find React Hook Form to be useful in your project, please consider starring and supporting it.