# Get Started > Get started with React Hook Form: install the library, register inputs, validate forms, and handle submission in React with minimal code and re-renders. Source: https://react-hook-form.com/get-started ## Quick start React Hook Form manages form values, validation, errors, and submission while working with standard React inputs. ### Install ```bash npm install react-hook-form ``` ### Build your first form This example registers an email field, validates it when the form is submitted, and passes valid data to `onSubmit`. **TS** ```tsx import { useForm, type SubmitHandler } from "react-hook-form" type FormValues = { email: string } export default function App() { const { register, handleSubmit, formState: { errors }, } = useForm({ defaultValues: { email: "" }, }) const onSubmit: SubmitHandler = (data) => console.log(data) return (
{errors.email &&

{errors.email.message}

}
) } ``` **JS** ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit, formState: { errors }, } = useForm({ defaultValues: { email: "" }, }) const onSubmit = (data) => console.log(data) return (
{errors.email &&

{errors.email.message}

}
) } ``` The example uses four fundamental pieces: - [`useForm`](https://react-hook-form.com/docs/useform) creates the form and its methods. - [`register`](https://react-hook-form.com/docs/useform/register) connects a native input to the form and attaches validation rules. - [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit) validates the form before it calls your submit handler. - [`formState.errors`](https://react-hook-form.com/docs/useform/formstate) contains the current validation errors. Use `defaultValues` for the initial value of every field. This gives React Hook Form one consistent baseline for dirty state, resetting, and controlled components. ### Choose your next step | If you want to… | Continue with… | | --------------------------------------------- | --------------------------------------------------------------------------------------------------- | | Validate native inputs | [Register fields](https://react-hook-form.com/get-started#Registerfields) and [Apply validation](https://react-hook-form.com/get-started#Applyvalidation) | | Use Zod, Yup, or another schema library | [Schema validation](https://react-hook-form.com/get-started#SchemaValidation) or [integration guides](https://react-hook-form.com/integrations) | | Connect shadcn/ui, MUI, React-Select, or AntD | [Controlled inputs](https://react-hook-form.com/get-started#IntegratingControlledInputs) | | Submit to an API or Server Action | [Form component](https://react-hook-form.com/docs/useform/form) | | Build with React Native | [React Native](https://react-hook-form.com/get-started#ReactNative) | | Add end-to-end TypeScript types | [TypeScript](https://react-hook-form.com/get-started#TypeScript) | ## React Web Video Tutorial This video tutorial illustrates the basic usage and concepts of React Hook Form. [Watch on YouTube](https://www.youtube.com/watch?v=RkXv4AXXC_4) ## Register fields One of the key concepts in React Hook Form is to **`register`** your component into the hook. This will make its value available for both the form validation and submission. **Note:** Each field is **required** to have a `name` as a key for the registration process. **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) ```tsx import { useForm, SubmitHandler } from "react-hook-form" enum GenderEnum { female = "female", male = "male", other = "other", } interface IFormInput { firstName: string gender: GenderEnum } export default function App() { const { register, handleSubmit } = useForm() const onSubmit: SubmitHandler = (data) => console.log(data) return (
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-get-started-j5wxo) ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit } = useForm() const onSubmit = (data) => console.log(data) return (
) } ``` ## Apply validation React Hook Form makes form validation easy by aligning with the existing [HTML standard for form validation](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation). List of validation rules supported: - required - min - max - minLength - maxLength - pattern - validate You can read more details on each rule in the [register section](https://react-hook-form.com/docs/useform/register). **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-apply-validation-ts-forked-nmbyh) ```tsx import { useForm, SubmitHandler } from "react-hook-form" interface IFormInput { firstName: string lastName: string age: number } export default function App() { const { register, handleSubmit } = useForm() const onSubmit: SubmitHandler = (data) => console.log(data) return (
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-apply-validation-q5m00) ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit } = useForm() const onSubmit = (data) => console.log(data) return (
) } ``` ## Integrating an existing form Integrating an existing form is simple. The important step is to register the component's ref and assign the relevant props to your input. **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-adapting-existing-form-ts-uzfxm) ```tsx import { forwardRef } from "react" import { FieldPath, useForm, UseFormRegister, SubmitHandler, } from "react-hook-form" interface IFormValues { "First Name": string Age: number } type InputProps = { label: FieldPath register: UseFormRegister required: boolean } // The following component is an example of your existing Input Component const Input = ({ label, register, required }: InputProps) => ( <> ) // you can use forwardRef to pass the ref too const Select = forwardRef< HTMLSelectElement, { label: string } & ReturnType> >(({ onChange, onBlur, name, label }, ref) => ( <> )) const App = () => { const { register, handleSubmit } = useForm() const onSubmit: SubmitHandler = (data) => { alert(JSON.stringify(data)) } return (
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-adapting-existing-form-llbnn) ```javascript import { forwardRef } from "react" import { useForm } from "react-hook-form" // The following component is an example of your existing Input Component const Input = ({ label, register, required }) => ( <> ) // you can use forwardRef to pass the ref too const Select = forwardRef(({ onChange, onBlur, name, label }, ref) => ( <> )) const App = () => { const { register, handleSubmit } = useForm() const onSubmit = (data) => { alert(JSON.stringify(data)) } return (
) } ``` ## Integrating with UI libraries React Hook Form has made it easy to integrate with external UI component libraries. If the component doesn't expose the input's `ref`, then you should use the [Controller](https://react-hook-form.com/docs/usecontroller/controller) component, which will take care of the registration process. **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-with-ui-library-ts-forked-qjgkx) ```tsx import Select from "react-select" import { useForm, Controller, SubmitHandler } from "react-hook-form" import { Input } from "@mui/material" interface IFormInput { firstName: string lastName: string iceCreamType: { label: string; value: string } } const App = () => { const { control, handleSubmit } = useForm({ defaultValues: { firstName: "", lastName: "", iceCreamType: { label: "", value: "" }, }, }) const onSubmit: SubmitHandler = (data) => { console.log(data) } return (
} /> ( ) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-with-ui-library-forked-fp5r3) ```javascript import Select from "react-select" import { useForm, Controller } from "react-hook-form" import { Input } from "@mui/material" const App = () => { const { control, handleSubmit } = useForm({ defaultValues: { firstName: "", select: {}, }, }) const onSubmit = (data) => console.log(data) return (
} /> ( ) } ``` ## Integrating Controlled Inputs This library embraces uncontrolled components and native HTML inputs. However, it's hard to avoid working with external controlled components such as [shadcn/ui](https://ui.shadcn.com/docs/components/form), [React-Select](https://github.com/JedWatson/react-select), [AntD](https://github.com/ant-design/ant-design) and [MUI](https://mui.com/). To make this simple, we provide a wrapper component, [Controller](https://react-hook-form.com/docs/usecontroller/controller), to streamline the integration process while still giving you the freedom to use a custom register. #### Using Component API **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) ```tsx import { useForm, Controller, SubmitHandler } from "react-hook-form" import { Checkbox } from "@mui/material" interface IFormInputs { MyCheckbox: boolean } function App() { const { handleSubmit, control, reset } = useForm({ defaultValues: { MyCheckbox: false, }, }) const onSubmit: SubmitHandler = (data) => console.log(data) return (
} /> ) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-controller-5h1q5) ```javascript import { useForm, Controller } from "react-hook-form" import { Checkbox } from "@mui/material" function App() { const { handleSubmit, control, reset } = useForm({ defaultValues: { MyCheckbox: false, }, }) const onSubmit = (data) => console.log(data) return (
} /> ) } ``` ```tsx import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form" import { z } from "zod" import { Form, FormControl, FormField } from "@/components/ui/form" import { Input } from "@/components/ui/input" const FormSchema = z.object({ username: z.string().min(2, { message: "Username must be at least 2 characters.", }), }) export function InputForm() { const form = useForm({ resolver: zodResolver(FormSchema), defaultValues: { username: "", }, }) function onSubmit(data: z.output) { console.log(data) } return (
( )} /> ) } ``` **Note:** The `shadcn/ui` example above requires installing `@hookform/resolvers` and `zod`: ```bash npm install @hookform/resolvers zod ``` If you hit `Cannot find module '@hookform/resolvers/zod'` (or `zod/v4/core`), it's almost always a version mismatch: Zod v4 support requires `@hookform/resolvers` ^3.10 or newer paired with `zod` ^3.25 or `zod` v4, and your `tsconfig.json` needs `"moduleResolution": "bundler"` (or `"node16"`/`"nodenext"`) so the package's subpath exports resolve correctly. See [react-hook-form/resolvers#839](https://github.com/react-hook-form/resolvers/issues/839) for details. #### Using Hooks API **TS** [Open in CodeSandbox](https://codesandbox.io/s/usecontroller-forked-4t8cx) ```tsx import { useForm, useController, UseControllerProps } from "react-hook-form" type FormValues = { FirstName: string } function Input(props: UseControllerProps) { const { field, fieldState } = useController(props) return (

{fieldState.isTouched && "Touched"}

{fieldState.isDirty && "Dirty"}

{fieldState.invalid ? "invalid" : "valid"}

) } export default function App() { const { handleSubmit, control } = useForm({ defaultValues: { FirstName: "", }, mode: "onChange", }) const onSubmit = (data: FormValues) => console.log(data) return (
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/usecontroller-tefsc) ```javascript import { TextField } from "@mui/material" import { useController, useForm } from "react-hook-form" function Input({ control, name }) { const { field, fieldState: { invalid, isTouched, isDirty }, formState: { touchedFields, dirtyFields }, } = useController({ name, control, rules: { required: true }, }) return ( ) } ``` ## Integrating with global state This library doesn't require you to rely on a state management library, but you can easily integrate with them. ```javascript import { useForm } from "react-hook-form" import { connect } from "react-redux" import updateAction from "./actions" function App(props) { const { register, handleSubmit, setValue } = useForm({ defaultValues: { firstName: "", lastName: "", }, }) // Submit your data into Redux store const onSubmit = (data) => props.updateAction(data) return (
) } // Connect your component with redux export default connect(({ firstName, lastName }) => ({ firstName, lastName }), { updateAction, })(App) ``` ## Handle errors React Hook Form provides an `errors` object to show you the errors in the form. `errors`' type will return given validation constraints. The following example showcases a required validation rule. [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-errormessage-multiple-error-messages-3ur2z) ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, formState: { errors }, handleSubmit, } = useForm() const onSubmit = (data) => console.log(data) return (
{errors.firstName?.type === "required" && (

First name is required

)} {errors.mail &&

{errors.mail.message}

}
) } ``` ## Integrating with services To integrate React Hook Form with a service, you can use the library's built-in submission handling. The `
` component allows you to easily send form data to an API endpoint or other service. [Find out more about the Form component](https://react-hook-form.com/docs/useform/form). ```javascript import { Form, useForm } from "react-hook-form" function App() { const { register, control } = useForm() return ( { alert("Your application is updated.") }} onError={() => { alert("Submission has failed.") }} control={control} >
) } ``` ## Schema Validation React Hook Form supports schema validation through the [`resolver`](https://react-hook-form.com/docs/useform#resolver) option. A resolver runs your schema against the complete form data and returns typed values or validation errors. Supported libraries include: For complete TypeScript examples with Zod and Yup, see the [React Hook Form integration guides](https://react-hook-form.com/integrations). See the full, up-to-date list in the [`@hookform/resolvers`](https://github.com/react-hook-form/resolvers) repo. **Step 1:** Install `Yup` into your project. ```bash npm install @hookform/resolvers yup ``` **Step 2:** Prepare your schema for validation and register inputs with React Hook Form. [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-validationschema-rm35t) ```javascript import { useForm } from "react-hook-form" import { yupResolver } from "@hookform/resolvers/yup" import * as yup from "yup" const schema = yup .object({ firstName: yup.string().required(), age: yup.number().positive().integer().required(), }) .required() export default function App() { const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: yupResolver(schema), }) const onSubmit = (data) => console.log(data) return (

{errors.firstName?.message}

{errors.age?.message}

) } ``` ## React Native You will get the same performance boost and enhancement in React Native. To integrate with input component, you can wrap it with `Controller`. [Open in Expo Snack](https://snack.expo.io/@bluebill1049/react-hook-form-v7---controller) ```javascript import { Text, View, TextInput, Button } from "react-native" import { useForm, Controller } from "react-hook-form" export default function App() { const { control, handleSubmit, formState: { errors }, } = useForm({ defaultValues: { firstName: "", lastName: "", }, }) const onSubmit = (data) => console.log(data) return ( ( )} name="firstName" /> {errors.firstName && This is required.} ( )} name="lastName" /> ) } ``` ## Design and philosophy React Hook Form's design and philosophy focus on user and developer experience. The library aims to provide users with a smoother interaction experience by fine-tuning the performance and improving accessibility. Some of the performance enhancements include: - Introducing form state subscription model through the proxy - Avoiding unnecessary computation - Isolating component re-rendering when required Overall, it improves the user experience as users interact with the application. For developers, we introduced built-in validation and are closely aligned with HTML standards, allowing further extension with powerful validation methods and native integration with schema validation. In addition, having a strongly type-checked form with the help of TypeScript provides early build-time feedback to help and guide developers in building a robust form solution. The following talk given by [Bill](https://twitter.com/bluebill1049) showcased some of the ideas and design patterns: [Watch on YouTube](https://www.youtube.com/watch?v=ZFxHdpzaEmM) ## Next steps Choose the path that matches what you are building next. - [Explore the API](https://react-hook-form.com/docs/useform) Understand every useForm option, method, and form-state property. - [Add schema validation](https://react-hook-form.com/integrations) Connect Zod, Yup, Valibot, or another supported resolver. - [Build advanced forms](https://react-hook-form.com/advanced-usage) Create accessible, reusable, tested, and multi-step form experiences. - [Solve common problems](https://react-hook-form.com/faqs) Find answers about performance, controlled inputs, validation, and testing. --- # React Hook Form Integrations > Integrate React Hook Form with Zod, Yup, every official schema resolver, Next.js, shadcn/ui, and React 19 using practical TypeScript examples. Source: https://react-hook-form.com/integrations React Hook Form works with schema validators, controlled UI components, and modern React frameworks without changing how your form data is managed. Choose an integration for installation steps, a complete example, TypeScript guidance, and integration-specific caveats. ## Schema validation - [Zod](https://react-hook-form.com/integrations/zod) — TypeScript-first schemas, input/output types, and transformed values. - [Yup](https://react-hook-form.com/integrations/yup) — object schemas, inferred types, casting, and form context. - [All schema resolvers](https://react-hook-form.com/integrations/resolvers) — AJV, ArkType, Class Validator, computed-types, Effect, fluentvalidation-ts, io-ts, Joi, Nope, Standard Schema, Superstruct, typanion, TypeBox, TypeSchema, Valibot, Vest, VineJS, ata-validator, Yup, and Zod. ## Frameworks and UI - [Next.js](https://react-hook-form.com/integrations/nextjs) — App Router Client Components, Server Actions, and server-side validation. - [shadcn/ui](https://react-hook-form.com/integrations/shadcn-ui) — `FormField`, controlled components, Zod, and accessible errors. - [React 19](https://react-hook-form.com/integrations/react-19) — form actions, progressive enhancement, and `useActionState`. ## Choose the right API | Goal | Recommended API | | -------------------------------------- | ---------------------------------------------------------------------------------------- | | Validate with an external schema | A [resolver](https://react-hook-form.com/integrations/resolvers) passed to [`useForm`](https://react-hook-form.com/docs/useform#resolver) | | Use a controlled UI component | [`Controller`](https://react-hook-form.com/docs/usecontroller/controller) or [`useController`](https://react-hook-form.com/docs/usecontroller) | | Share methods through a component tree | [`FormProvider`](https://react-hook-form.com/docs/formprovider) and [`useFormContext`](https://react-hook-form.com/docs/useformcontext) | | Submit to an endpoint or Server Action | [`Form`](https://react-hook-form.com/docs/useform/form) | | Own the complete request lifecycle | [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit) | | Build repeatable dynamic rows | [`useFieldArray`](https://react-hook-form.com/docs/usefieldarray) | For the fundamentals, begin with [Get Started](https://react-hook-form.com/get-started). Continue to [Advanced Usage](https://react-hook-form.com/advanced-usage) for accessibility, testing, reusable components, and Server Action patterns. --- # React Hook Form with Next.js > Use React Hook Form with Next.js App Router and Server Actions, including Client Components, progressive enhancement, and server validation. Source: https://react-hook-form.com/integrations/nextjs Call `useForm` from a Client Component in the Next.js App Router. Submit with [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit), or pass a Server Action to React Hook Form's [`Form` component](https://react-hook-form.com/docs/useform/form). ## Create the Server Action ```tsx // app/profile/actions.ts "use server" export async function updateProfile(formData: FormData) { const name = String(formData.get("name") ?? "") if (!name) throw new Error("Name is required") // Authenticate, validate again, then update the database. } ``` ## Build the Client Component ```tsx // app/profile/profile-form.tsx "use client" import { Form, useForm } from "react-hook-form" import { updateProfile } from "./actions" export function ProfileForm() { const { control, register, formState: { errors, isSubmitting, isSubmitSuccessful }, } = useForm<{ name: string }>({ progressive: true }) return (
{errors.name &&

{errors.name.message}

} {errors.root?.server &&

Could not save your profile.

} {isSubmitSuccessful &&

Profile saved.

}
) } ``` `progressive: true` forwards compatible validation rules as native HTML attributes, allowing useful validation before hydration. After hydration, React Hook Form manages validation. ## Server validation is still required Client validation improves feedback but is not a security boundary. Authenticate the request, authorize the operation, and validate every untrusted value inside the Server Action. Map returned field errors with [`setError`](https://react-hook-form.com/docs/useform/seterror) when the server needs to report a specific input. ## Choosing a submission pattern - Use [`Form`](https://react-hook-form.com/docs/useform/form) for a direct Server Action or conventional API request. - Use [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit) when you need retries, cancellation, or a data-fetching library. - Use React's `useActionState` when the action result drives UI beyond React Hook Form's `formState`. See [Server Actions and useActionState](https://react-hook-form.com/advanced-usage/server-actions), [Zod validation](https://react-hook-form.com/integrations/zod), and [React 19 forms](https://react-hook-form.com/integrations/react-19). --- # React Hook Form with React 19 > Use React Hook Form with React 19 form actions, progressive enhancement, Server Actions, useActionState, validation, and submission state. Source: https://react-hook-form.com/integrations/react-19 React 19 form actions and React Hook Form solve complementary problems. React actions coordinate mutations and returned state; React Hook Form manages field registration, client validation, errors, dirty state, and fine-grained subscriptions. ## Submit to an action Pass a function to the [`Form` component's `action` prop](https://react-hook-form.com/docs/useform/form#Props). The action receives `FormData` after client validation succeeds. ```tsx "use client" import { Form, useForm } from "react-hook-form" import { createAccount } from "./actions" export function AccountForm() { const { control, register, formState: { errors, isSubmitting, isSubmitSuccessful }, } = useForm<{ email: string }>({ progressive: true }) return (
{errors.email &&

{errors.email.message}

} {errors.root?.server &&

Could not create the account.

} {isSubmitSuccessful &&

Account created.

}
) } ``` With `progressive: true`, compatible rules are rendered as native attributes before hydration. React Hook Form takes over validation after hydration. ## When to use useActionState Use React's `useActionState` when the value returned by an action drives additional UI, such as a server-generated confirmation or multiple field errors. Map server field errors to React Hook Form with [`setError`](https://react-hook-form.com/docs/useform/seterror). Use React Hook Form's `formState` when you mainly need: - `errors`, `isValid`, and validation state - `isDirty`, `dirtyFields`, and touched state - `isSubmitting` and `isSubmitSuccessful` - isolated subscriptions through [`useFormState`](https://react-hook-form.com/docs/useformstate) ## Avoid duplicate submissions Choose one owner for the request. Give `Form` an `action`, or omit it and send the request inside `onSubmit`. Supplying both means `onSubmit` runs first and then the action runs. See the [Next.js guide](https://react-hook-form.com/integrations/nextjs), [`Form` API](https://react-hook-form.com/docs/useform/form), and [advanced useActionState example](https://react-hook-form.com/advanced-usage/server-actions). --- # React Hook Form Schema Resolvers > Compare every official React Hook Form resolver for Zod, Yup, Valibot, ArkType, AJV, Joi, TypeBox, Standard Schema, and more. Source: https://react-hook-form.com/integrations/resolvers The [`@hookform/resolvers`](https://github.com/react-hook-form/resolvers) package connects external validation libraries to [`useForm`](https://react-hook-form.com/docs/useform). A resolver receives the complete form values, validates them against a schema, and returns normalized values and errors. ## Installation Install React Hook Form, the resolver package, and your chosen schema library: ```bash npm install react-hook-form @hookform/resolvers ``` Every adapter follows the same integration pattern: ```tsx import { useForm } from "react-hook-form" import { libraryResolver } from "@hookform/resolvers/library" const form = useForm({ resolver: libraryResolver(schema), }) ``` ## Resolver comparison “Infers values” means the resolver can infer the submitted output from its schema. `criteriaMode` describes whether the adapter can return only the first error or all errors for a field. | Schema library | Resolver | Install | Infers values | `criteriaMode` | | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | --------------------------------------- | ------------- | ------------------- | | [AJV](https://github.com/ajv-validator/ajv) | `ajvResolver` from `@hookform/resolvers/ajv` | `ajv` | No | `firstError \| all` | | [ata-validator](https://github.com/nicholasgasior/ata-validator) | `ataResolver` from `@hookform/resolvers/ata-validator` | `ata-validator` | No | `firstError \| all` | | [ArkType](https://github.com/arktypeio/arktype) | `arktypeResolver` from `@hookform/resolvers/arktype` | `arktype` | Yes | `firstError` | | [Class Validator](https://github.com/typestack/class-validator) | `classValidatorResolver` from `@hookform/resolvers/class-validator` | `class-validator` | Yes | `firstError \| all` | | [computed-types](https://github.com/neuledge/computed-types) | `computedTypesResolver` from `@hookform/resolvers/computed-types` | `computed-types` | Yes | `firstError` | | [Effect](https://github.com/Effect-TS/effect) | `effectTsResolver` from `@hookform/resolvers/effect-ts` | `effect` | Yes | `firstError \| all` | | [fluentvalidation-ts](https://github.com/AlexJPotter/fluentvalidation-ts) | `fluentValidationResolver` from `@hookform/resolvers/fluentvalidation-ts` | `fluentvalidation-ts` | No | `firstError` | | [io-ts](https://github.com/gcanti/io-ts) | `ioTsResolver` from `@hookform/resolvers/io-ts` | `io-ts` | Yes | `firstError` | | [Joi](https://github.com/sideway/joi) | `joiResolver` from `@hookform/resolvers/joi` | `joi` | No | `firstError \| all` | | [Nope](https://github.com/bvego/nope-validator) | `nopeResolver` from `@hookform/resolvers/nope` | `nope-validator` | No | `firstError` | | [Standard Schema](https://github.com/standard-schema/standard-schema) | `standardSchemaResolver` from `@hookform/resolvers/standard-schema` | A compatible schema library | Yes | `firstError \| all` | | [Superstruct](https://github.com/ianstormtaylor/superstruct) | `superstructResolver` from `@hookform/resolvers/superstruct` | `superstruct` | Yes | `firstError` | | [typanion](https://github.com/arcanis/typanion) | `typanionResolver` from `@hookform/resolvers/typanion` | `typanion` | Yes | `firstError` | | [TypeBox](https://github.com/sinclairzx81/typebox) | `typeboxResolver` from `@hookform/resolvers/typebox` | `@sinclair/typebox` | Yes | `firstError \| all` | | [TypeSchema](https://github.com/decs/typeschema) | `typeschemaResolver` from `@hookform/resolvers/typeschema` | `@typeschema/main` and a schema library | No | `firstError \| all` | | [Valibot](https://github.com/fabian-hiller/valibot) | `valibotResolver` from `@hookform/resolvers/valibot` | `valibot` | Yes | `firstError \| all` | | [Vest](https://github.com/ealush/vest) | `vestResolver` from `@hookform/resolvers/vest` | `vest` | No | `firstError \| all` | | [VineJS](https://github.com/vinejs/vine) | `vineResolver` from `@hookform/resolvers/vine` | `@vinejs/vine` | Yes | `firstError \| all` | | [Yup](https://react-hook-form.com/integrations/yup) | `yupResolver` from `@hookform/resolvers/yup` | `yup` | Yes | `firstError \| all` | | [Zod](https://react-hook-form.com/integrations/zod) | `zodResolver` from `@hookform/resolvers/zod` | `zod` | Yes | `firstError \| all` | ## Resolver options Resolvers accept an optional third argument: ```tsx resolver(schema, schemaOptions, { mode: "async", // or "sync" raw: false, }) ``` - Async mode is the default. Use `sync` only when the schema performs no asynchronous work. - Set `raw: true` when submitted values should remain unparsed instead of using the schema's transformed output. - Pass a form value type to `useForm` when the comparison table says inference is unavailable. For detailed working examples, see the dedicated [Zod guide](https://react-hook-form.com/integrations/zod) and [Yup guide](https://react-hook-form.com/integrations/yup). The [official resolvers repository](https://github.com/react-hook-form/resolvers) maintains quick starts for every adapter. --- # React Hook Form with shadcn/ui > Use React Hook Form with shadcn/ui FormField, controlled components, Zod validation, default values, and accessible error messages. Source: https://react-hook-form.com/integrations/shadcn-ui The [shadcn/ui Form component](https://ui.shadcn.com/docs/components/form) composes React Hook Form's [`FormProvider`](https://react-hook-form.com/docs/formprovider) and [`Controller`](https://react-hook-form.com/docs/usecontroller/controller). It supplies accessible labels, descriptions, and error messages around shadcn/ui controls. ## Installation Add the shadcn/ui form primitives, then install the resolver and schema library used by this example: ```bash npx shadcn@latest add form input button npm install @hookform/resolvers zod ``` ## Complete example ```tsx "use client" import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form" import { z } from "zod" import { Button } from "@/components/ui/button" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" const schema = z.object({ username: z.string().min(2, "Enter at least two characters"), }) export function UsernameForm() { const form = useForm>({ resolver: zodResolver(schema), defaultValues: { username: "" }, }) return (
( Username )} /> ) } ``` ## Two different Form components The shadcn/ui `Form` above provides React Hook Form context. It is different from React Hook Form's submission-oriented [`Form` component](https://react-hook-form.com/docs/useform/form), which can send values to an endpoint or Server Action. ## Native and controlled inputs - Use `register` directly when a component exposes a native input ref and standard change events. - Use shadcn/ui `FormField` or React Hook Form's `Controller` for controlled components such as custom selects, date pickers, and switches. - Define every controlled field in `defaultValues`; avoid `undefined` as a controlled value. - Spread `field` onto the actual control so `value`, `onChange`, `onBlur`, `name`, and `ref` stay connected. See the dedicated [Zod guide](https://react-hook-form.com/integrations/zod), [`Controller`](https://react-hook-form.com/docs/usecontroller/controller), and [`FormProvider`](https://react-hook-form.com/docs/formprovider). --- # React Hook Form with Yup > Use React Hook Form with Yup and yupResolver. Learn installation, TypeScript inference, validation errors, schema casting, and form context. Source: https://react-hook-form.com/integrations/yup Use [`yupResolver`](https://github.com/react-hook-form/resolvers#yup) to connect a Yup object schema to React Hook Form. The resolver validates before submission and maps Yup errors into [`formState.errors`](https://react-hook-form.com/docs/useform/formstate). ## Installation ```bash npm install react-hook-form @hookform/resolvers yup ``` ## Complete TypeScript example ```tsx import { yupResolver } from "@hookform/resolvers/yup" import { useForm } from "react-hook-form" import * as yup from "yup" const schema = yup .object({ name: yup.string().required("Name is required"), email: yup.string().email("Enter a valid email").required(), }) .required() type FormValues = yup.InferType export function ContactForm() { const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: yupResolver(schema) }) return (
{errors.name &&

{errors.name.message}

} {errors.email &&

{errors.email.message}

}
) } ``` ## Passing context to Yup Pass dynamic validation context through `useForm`, not through the resolver's schema options. React Hook Form's context takes precedence. ```tsx useForm({ resolver: yupResolver(schema), context: { plan: "paid" }, }) ``` ## Common issues - Use `yup.InferType` to keep form values aligned with the schema. - Decide whether Yup should cast values or whether inputs should use `valueAsNumber` and `setValueAs`. - Avoid defining the same rule in both Yup and `register`. - Set `criteriaMode: "all"` when the UI should show every failing rule for a field. See [all schema resolvers](https://react-hook-form.com/integrations/resolvers), [`useForm`](https://react-hook-form.com/docs/useform), and the [TypeScript guide](https://react-hook-form.com/ts). --- # React Hook Form with Zod > Use React Hook Form with Zod and zodResolver. Learn installation, TypeScript inference, transformed values, errors, and numeric input validation. Source: https://react-hook-form.com/integrations/zod Use [`zodResolver`](https://github.com/react-hook-form/resolvers#zod) to validate form values against a Zod schema. Zod issues become React Hook Form errors available through [`formState.errors`](https://react-hook-form.com/docs/useform/formstate). ## Installation ```bash npm install react-hook-form @hookform/resolvers zod ``` ## Complete TypeScript example ```tsx import { zodResolver } from "@hookform/resolvers/zod" import { useForm, type SubmitHandler } from "react-hook-form" import { z } from "zod" const schema = z.object({ email: z.string().email("Enter a valid email address"), age: z.number().min(18, "You must be at least 18"), }) type FormValues = z.infer export function ProfileForm() { const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: zodResolver(schema) }) const onSubmit: SubmitHandler = (data) => console.log(data) return (
{errors.email &&

{errors.email.message}

} {errors.age &&

{errors.age.message}

}
) } ``` `valueAsNumber` converts the browser's input string before Zod receives it. Without it, a `z.number()` schema receives a string unless the schema performs its own coercion. ## Input and output types Most schemas infer the submitted output automatically. When a schema transforms its input, declare both sides explicitly: ```tsx useForm, unknown, z.output>({ resolver: zodResolver(schema), }) ``` Use `z.input` for values entered by the form and `z.output` for the parsed data received by `handleSubmit`. ## Common issues - Keep validation rules in the schema instead of duplicating them in `register`. - Use `z.coerce.number()` or `valueAsNumber` for numeric HTML inputs. - Give controlled components a defined `defaultValue` or `defaultValues` entry. - For all messages from a field, use `criteriaMode: "all"` and render the collected error types. See [all schema resolvers](https://react-hook-form.com/integrations/resolvers), [`useForm`](https://react-hook-form.com/docs/useform), and the [TypeScript guide](https://react-hook-form.com/ts). --- # createFormControl > Create standalone React Hook Form state outside of a React component, useful for global or shared form state management across your app. Source: https://react-hook-form.com/docs/createFormControl ## `createFormControl:` ([UseFormProps](https://react-hook-form.com/ts#UseFormProps)) => object _(since v7.55.0)_ This function creates the entire form state subscription and allows you to subscribe to updates with or without a React component. You can use this function without needing the React Context API. ### Props --- | Name | Type | Description | | ---------- | --------------------------- | -------------- | | `...props` | `Object` | `UseFormProps` | ### Return --- | Name | Type | Description | | ------------- | ------------------------------ | ----------------------------------------------------------------------------------------- | | `formControl` | `Object` | control object for `useForm` hook | | `control` | `Object` | control object for `useController`, `useFormState`, `useWatch` | | `subscribe` | `Function` | function to [subscribe](https://react-hook-form.com/docs/useform/subscribe) for form state updates without rendering | | `...returns` | `Functions` | `useForm` return methods | > **Important: Notes** > - This function is completely optional; you can consider using this instead of > the `useFormContext` API. - You may find it useful if you would like to > subscribe to `formState` while skipping React re-renders. > **Important: Rules** > > - You should either use this API or the Context API > > ```tsx > const props = createFormControl() > > // ❌ You don't need a provider > > // ✅ Use method directly from createFormControl > ``` > > - Create the control once. Passing a new instance to `useForm({ formControl })` re-initializes the form. A control created at module scope is a single form shared by every component that uses it and, during server rendering, by every request. For one form per component instance, create it lazily: > > ```tsx > const [form] = useState(() => createFormControl({ defaultValues })) > const { register } = useForm({ formControl: form.formControl }) > ``` > ### Examples --- **Setup** ```javascript const { formControl, control, handleSubmit, register } = createFormControl({ mode: "onChange", defaultValues: { firstName: "Bill", }, }) function App() { useForm({ formControl, }) return (
console.log(data))}> ) } function FormState() { const { isDirty } = useFormState({ control, // no longer need context api }) return isDirty ?

Form is dirty.

: null } function ControlledInput() { const { field } = useController({ control, // no longer need context api name: "firstName", }) return } ``` **Subscribe** ```javascript const { formControl, register } = createFormControl(props) formControl.subscribe({ formState: { isDirty: true, values: true, }, callback: (formState) => { if (formState.isDirty) { // do something here } if (formState.values.test.length > 3) { // do something here } }, }) function App() { const { register } = useForm({ formControl, }) return (
) } ``` ### Tips --- - Use the returned `handleSubmit`, `setValue`, `reset`, and other methods anywhere that can import the control, such as a toolbar button that is outside the form's component tree. - To sync form values to an external store, call `subscribe` and pick only the state you need. Call the returned function to unsubscribe when you no longer need updates: ```javascript const unsubscribe = formControl.subscribe({ formState: { values: true }, callback: ({ values }) => store.setDraft(values), }) ``` - In tests, you can create a control, render your form with it, and then call methods like `setValue` or `trigger` directly, without simulating every user event. ### Troubleshooting --- #### Two forms unexpectedly share values and errors **Why it happens:** They use the same `createFormControl` instance. A control created at module scope is a singleton, so every component—and every server request—can share its state. **Fix:** Create one stable control per form instance: ```javascript const [form] = useState(() => createFormControl({ defaultValues: { name: "" } }) ) ``` Do not recreate it on every render, and avoid a module-scoped control during server rendering. #### Form state changes but the React UI does not update **Why it happens:** Calling methods on a standalone control updates the form, but React components only re-render for state they subscribe to. **Fix:** Connect the control with `useForm({ formControl })`, and read reactive state with `useFormState({ control })` or values with `useWatch({ control })`. Use `formControl.subscribe` only for side effects that do not render UI. --- # FormProvider > Wrap your form tree with FormProvider to share useForm methods across deeply nested components without passing props manually. Source: https://react-hook-form.com/docs/formprovider ## `FormProvider`: [FormProviderProps](https://react-hook-form.com/ts#FormProviderProps) This component hosts the context object and allows consuming components to subscribe to context and use [useForm](https://react-hook-form.com/docs/useform) props and methods. ### Props --- The following table applies to `FormProvider`; `useFormContext` accepts no arguments. | Name | Type | Description | | ---------- | --------------------------- | ---------------------------------------------- | | `...props` | `Object` | `FormProvider` requires all `useForm` methods. | > **Important: Rules** > > - Avoid nesting `FormProvider` components. Because React context does not merge, any `useFormContext()` call inside the inner `FormProvider`'s subtree will only see the _innermost_ form's methods and state — not the outer form — which can silently break field registration or validation for consumers that expect the outer form. > - _(since v7.44.0)_ `FormProviderProps` accepts a `TTransformedValues` generic (`FormProviderProps`) to type a resolver's transformed output. > ### Examples --- [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi) ```javascript import { useEffect } from "react" import { useForm, FormProvider, useFormContext } from "react-hook-form" export default function App() { const methods = useForm() const onSubmit = (data) => console.log(data) const { register, reset } = methods useEffect(() => { reset({ name: "data", }) }, [reset]) // ❌ never put `methods` as a dependency return (
) } function NestedInput() { const { register } = useFormContext() // retrieve all hook methods return } ``` ### Tips --- - Spread the whole `useForm` return value: ``. If you pass only some methods, child components that call [`useFormContext`](https://react-hook-form.com/docs/useformcontext) get an object with missing methods. - Inside a `FormProvider`, hooks such as [`useController`](https://react-hook-form.com/docs/usecontroller), [`useWatch`](https://react-hook-form.com/docs/usewatch), [`useFormState`](https://react-hook-form.com/docs/useformstate), and [`useFieldArray`](https://react-hook-form.com/docs/usefieldarray) can leave out `control`. They read it from context. - To have two forms on one page, render two `FormProvider`s next to each other, not one inside the other. - To share a form without React context, see [`createFormControl`](https://react-hook-form.com/docs/createFormControl). ### Troubleshooting --- #### `handleSubmit is not a function` (or another method is `undefined`) **Why it happens:** Only some methods were passed to `FormProvider`, for example ``. `useFormContext()` returns exactly what the provider received, so the other methods are missing. **Fix:** Spread the whole `useForm` return value: ``. #### A field inside a nested `FormProvider` is missing from the submitted data **Why it happens:** `useFormContext` uses the nearest `FormProvider`. When one provider is rendered inside another, fields under the inner one register with the inner form, and the outer form's `handleSubmit` never sees them. **Fix:** Use one `FormProvider` per form. To show two forms on one page, render the providers next to each other, not one inside the other. --- # useController > React hook for building reusable controlled inputs with full access to field value, validation state, and form state from React Hook Form. Source: https://react-hook-form.com/docs/usecontroller ## `useController:` ([UseControllerProps](https://react-hook-form.com/ts#UseControllerProps)) => [UseControllerReturn](https://react-hook-form.com/ts#UseControllerReturn) This custom hook powers [`Controller`](https://react-hook-form.com/docs/usecontroller/controller). Additionally, it shares the same props and methods as `Controller`. It's useful for creating reusable Controlled input. ### Props --- The following table contains information about the arguments for `useController`. | Name | Type | Required | Description | | ------------------ | ----------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `name` | [FieldPath](https://react-hook-form.com/ts#FieldPath) | ✓ | Unique name of your input. Reactive — the controller re-subscribes when this prop changes, allowing dynamic field name switching. | | `control` | [Control](https://react-hook-form.com/ts#Control) | | [`control`](https://react-hook-form.com/docs/useform/control) object provided by invoking `useForm`. Optional when using `FormProvider`. | | `rules` | `Object` | | Validation rules in the same format for `register`, which includes: `required`, `min`, `max`, `minLength`, `maxLength`, `pattern`, `validate`.

`rules={{ required: true }}` | | `shouldUnregister` | `boolean = false` | | Input will be unregistered after unmount and defaultValues will be removed as well. **Note:** this prop should be avoided when using with `useFieldArray` as `unregister` function gets called after input unmount/remount and reorder. | | `disabled` | `boolean = false` | | _(since v7.46.0)_ `disabled` prop will be returned from `field` prop. Controlled input will be disabled and its value will be omitted from the submission data. | | `defaultValue` | `unknown` | | **Important:** Cannot apply `undefined` to `defaultValue` or `defaultValues` at `useForm`.
  • You need to either set `defaultValue` at the field-level or `useForm`'s `defaultValues`. `undefined` is not a valid value. If you used `defaultValues` at `useForm`, skip using this prop.
  • If your form will invoke `reset` with default values, you will need to provide `useForm` with `defaultValues`.
  • If `field.value` is `undefined` on first render, the input starts out uncontrolled and React will warn when it later becomes controlled — always set `defaultValue`/`defaultValues` to avoid this.
| | `exact` | `boolean = true` | | _(since v7.68.0)_ This prop will enable an exact match for input name subscriptions, default to true. _(since v7.81.0)_ With `exact: true`, the field is also updated when one of its ancestor paths is set (for example, a field named `"users.0.name"` reflects `setValue("users.0", { name: "Jane" })`), but not when a nested child path of its value changes (for example, `setValue("users.0.name", "Jane")` does not update a field named `"users.0"`). Pass `exact: false` to also receive nested updates. **Note:** this differs from [`useWatch`](https://react-hook-form.com/docs/usewatch) and [`useFormState`](https://react-hook-form.com/docs/useformstate), which both default `exact` to `false`. | ### Return --- The following table contains information about properties which `useController` produces. | Object Name | Name | Type | Description | | ------------ | -------------------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `field` | `onChange` | `(value: any) => void` | A function which sends the input's value to the library. It should be assigned to the `onChange` prop of the input and value should **not be `undefined`**. This prop updates [formState](https://react-hook-form.com/docs/useform/formstate) and you should avoid manually invoking [`setValue`](https://react-hook-form.com/docs/useform/setvalue) or other API related to field update. It accepts either a change event or a value: given an event, it reads `target.checked` for checkboxes, `target.files` for file inputs and `target.value` otherwise. Any object with a `target` property is treated as an event. | | `field` | `onBlur` | `() => void` | A function which sends the input's onBlur event to the library. It should be assigned to the input's `onBlur` prop. | | `field` | `value` | `unknown` | The current value of the controlled component. | | `field` | `disabled` | `boolean` | The disabled state of the input. | | `field` | `name` | `string` | Input's name being registered. | | `field` | `ref` | `React.Ref` | A ref used to connect hook form to the input. Assign `ref` to component's input ref to allow hook form to focus the error input. | | `fieldState` | `invalid` | `boolean` | Invalid state for current input. | | `fieldState` | `isTouched` | `boolean` | Touched state for current controlled input. | | `fieldState` | `isDirty` | `boolean` | Dirty state for current controlled input. | | `fieldState` | `isValidating` | `boolean` | Validating state for current controlled input. | | `fieldState` | `error` | `object` | _(since v7.0.0)_ error for this specific input. | | `formState` | `isDirty` | `boolean` | Set to `true` after the user modifies any of the inputs. **Important:** Make sure to provide all inputs' `defaultValues` at `useForm`, so hook form can have a single source of truth to compare whether the form is dirty. | | `formState` | `dirtyFields` | `object` | An object with the user-modified fields. Make sure to provide all inputs' `defaultValues` via `useForm`, so the library can compare against the `defaultValues`. | | `formState` | `touchedFields` | `object` | An object containing all the inputs the user has interacted with. | | `formState` | `defaultValues` | `object` | _(since v7.37.0)_ The value that was set in [`useForm`](https://react-hook-form.com/docs/useform)'s `defaultValues` or updated `defaultValues` via [`reset`](https://react-hook-form.com/docs/useform/reset) API. | | `formState` | `isSubmitted` | `boolean` | Set to `true` after the form is submitted. Will remain `true` until the `reset` method is invoked. | | `formState` | `isSubmitSuccessful` | `boolean` | Indicates that the form was successfully submitted without any runtime error. | | `formState` | `isSubmitting` | `boolean` | `true` if the form is currently being submitted. `false` otherwise. | | `formState` | `isLoading` | `boolean` | _(since v7.41.0)_ `true` if the form is currently loading async default values. **Important:** this prop is only applicable to async `defaultValues`. | | `formState` | `submitCount` | `number` | The number of times the form was submitted. | | `formState` | `isValid` | `boolean` | Set to `true` if the form doesn't have any errors. `setError` immediately forces `isValid` to `false`; this value is not itself derived from validation and will be overwritten the next time validation runs (e.g. on the next `onChange`, submit, or `trigger()` call). | | `formState` | `isValidating` | `boolean` | Set to `true` during validation. | | `formState` | `validatingFields` | `object` | _(since v7.51.0)_ Captures fields that are undergoing asynchronous validation. | | `formState` | `errors` | `object` | An object with field errors. There is also an [ErrorMessage](https://react-hook-form.com/docs/useformstate/errormessage) component to retrieve error messages easily. | | `formState` | `disabled` | `boolean` | _(since v7.48.0)_ Set to `true` if the form is disabled via the `disabled` prop in [`useForm`](https://react-hook-form.com/docs/useform#disabled). | | `formState` | `isReady` | `boolean` | _(since v7.56.0)_ Set to true when `formState` subscription setup is ready. | ### Examples ---
**JS** [Open in CodeSandbox](https://codesandbox.io/s/usecontroller-i0ywh) ```javascript import { TextField } from "@mui/material" import { useController, useForm } from "react-hook-form" function Input({ control, name, label }) { const { field, fieldState } = useController({ name, control, rules: { required: `${label} is required` }, }) return ( ) } export default function App() { const { handleSubmit, control } = useForm({ defaultValues: { firstName: "" }, }) return (
console.log(data))}>
) } ``` **TS** [Open in CodeSandbox](https://codesandbox.io/s/usecontroller-0o8px) ```tsx import { useForm, useController, UseControllerProps } from "react-hook-form" type FormValues = { FirstName: string } function Input(props: UseControllerProps) { const { field, fieldState } = useController(props) return (

{fieldState.isTouched && "Touched"}

{fieldState.isDirty && "Dirty"}

{fieldState.invalid ? "invalid" : "valid"}

) } export default function App() { const { handleSubmit, control } = useForm({ defaultValues: { FirstName: "", }, mode: "onChange", }) const onSubmit = (data: FormValues) => console.log(data) return (
) } ```
[Open in CodeSandbox](https://codesandbox.io/s/usecontroller-checkboxes-99ld4) ```javascript import { useState } from "react" import { useController, useForm } from "react-hook-form" const Checkboxes = ({ options, control, name }) => { const { field } = useController({ control, name, }) const [value, setValue] = useState(field.value || []) return ( <> {options.map((option, index) => ( { const valueCopy = [...value] // update checkbox value valueCopy[index] = e.target.checked ? e.target.value : null // send data to react hook form field.onChange(valueCopy) // update local state setValue(valueCopy) }} key={option} checked={value.includes(option)} type="checkbox" value={option} /> ))} ) } export default function App() { const { register, handleSubmit, control } = useForm({ defaultValues: { controlled: [], uncontrolled: [], }, }) const onSubmit = (data) => console.log(data) return (

uncontrolled

controlled

) } ```
A generic component built on `useController` works with any form, and TypeScript still checks that `name` is a field of the form that `control` belongs to. ```tsx import { useForm, useController, UseControllerProps, FieldValues, } from "react-hook-form" function TextInput(props: UseControllerProps) { const { field, fieldState } = useController(props) return (
{fieldState.error &&

{fieldState.error.message}

}
) } type FormValues = { firstName: string; lastName: string } export default function App() { const { control, handleSubmit } = useForm({ defaultValues: { firstName: "", lastName: "" }, }) return (
console.log(data))}> ) } ```
### Tips --- - It's important to be aware of each prop's responsibility when working with external controlled components, such as MUI, AntD, Chakra UI. Its job is to spy on the input, report, and set its value. - **onChange**: send data back to hook form - **onBlur**: report that the input has been interacted with (focus and blur) - **value**: set up input initial and updated value - **ref**: allow input to be focused with error — this only works if the target component forwards refs (`React.forwardRef`) or exposes an equivalent, like MUI's `inputRef`. If it doesn't accept a ref at all, omit `ref` from what you spread and handle focus manually. - **name**: give input an unique name It's fine to host your state and combined with `useController`. [Open in CodeSandbox](https://codesandbox.io/s/usecontroller-own-state-wncet2?file=/src/App.tsx) ```javascript const { field } = useController({ name: 'test' }); const [value, setValue] = useState(field.value); onChange={(event) => { // data sent back to hook form; empty input becomes null instead of NaN field.onChange(event.target.value === "" ? null : event.target.valueAsNumber) setValue(event.target.value) // UI state }} ``` - **Focusing components that don't forward a DOM ref:** `field.ref` accepts any object with a `focus` method (and optionally `select`), so you can point it at the component's own focus API: ```javascript field.ref(instance && { focus: () => instance.focusInput() }) } /> ``` - Do not `register` the input again. This custom hook is designed to take care of the registration process. ```javascript const { field } = useController({ name: 'test' }) // ✅ // ❌ double up the registration ``` - It's best to use a single `useController` call per component — each call creates its own subscription, so multiple calls in one component can cause extra re-renders. If you need more than one controlled field in the same component, rename the destructured `field` for each call to avoid naming collisions, or consider using `Controller` instead. ```javascript const { field: input } = useController({ name: 'test' }) const { field: checkbox } = useController({ name: 'test1' }) ``` ### Troubleshooting --- #### `A component is changing an uncontrolled input to be controlled` **Why it happens:** The field has no default value, so `field.value` is `undefined` on the first render. When the user types, the value becomes a string, and React warns that the input changed from uncontrolled to controlled. **Fix:** Give the field a default value in `useForm`, even if it is just `""`: ```javascript useForm({ defaultValues: { firstName: "" } }) ``` You can also pass `defaultValue` to `useController`. #### Changing `defaultValue` does not update the input **Why it happens:** The `defaultValue` option of `useController` is only read when the field first registers. Changing it later does not update the field. **Fix:** Use `reset` or `setValue` to change the value after the first render, or pass data that loads later to [`values`](https://react-hook-form.com/docs/useform#values) on `useForm`. #### `Cannot read properties of null (reading '_names')` **Why it happens:** `useController` could not find a form: no `control` was passed and the component is not inside a [`FormProvider`](https://react-hook-form.com/docs/formprovider). **Fix:** Pass `control` from `useForm`, or wrap the tree in ``. See [`control`](https://react-hook-form.com/docs/useform/control#Cannotreadpropertiesofnullreadingnames). --- # Controller > Wrapper component for integrating controlled external inputs like MUI, Chakra UI, and React-Select with React Hook Form validation. Source: https://react-hook-form.com/docs/usecontroller/controller ## `Controller`: [ControllerProps](https://react-hook-form.com/ts#ControllerProps) React Hook Form embraces uncontrolled components and native inputs; however, it's hard to avoid working with external controlled components such as [React-Select](https://github.com/JedWatson/react-select), [AntD](https://github.com/ant-design/ant-design) and [MUI](https://mui.com/). This wrapper component makes it easier for you to work with them. **Note:** if you simply want to control a field's value from outside the form, it's not necessary to use `Controller`. You can simply use the [`values`](https://react-hook-form.com/docs/useform#values) option of `useForm`. ### Props --- The following table contains information about the arguments for `Controller`. | Name | Type | Required | Description | | ------------------ | ------------------------------------------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `name` | [`FieldPath`](/ts#FieldPath "FieldPath type") | ✓ | Unique name of your input. | | `control` | [`Control`](/ts#Control "Control type") | | The [`control`](https://react-hook-form.com/docs/useform/control) object is from invoking `useForm`. Optional when using `FormProvider`. | | `render` | `Function` | ✓ | This is a [render prop](https://legacy.reactjs.org/docs/render-props.html). A function that returns a React element and provides the ability to attach events and value into the component. This simplifies integrating with external controlled components with non-standard prop names. Provides `field` (with `onChange`, `onBlur`, `name`, `ref`, `value`), `fieldState`, and `formState` objects to the render callback. | | `rules` | `Object` | | Validation rules in the same format for [`register` options](https://react-hook-form.com/docs/useform/register#options), which includes:

required, min, max, minLength, maxLength, pattern, validate | | `shouldUnregister` | `boolean = false` | | Input will be unregistered after unmount and defaultValues will be removed as well.

**Note:** this prop should be avoided when using with `useFieldArray` as `unregister` function gets called after input unmount/remount and reorder. | | `disabled` | `boolean = false` | | _(since v7.46.0)_ `disabled` prop will be returned from `field` prop. Controlled input will be disabled and its value will be omitted from the submission data. | | `defaultValue` | `unknown` | | **Important:** Cannot apply `undefined` to `defaultValue` or `defaultValues` at `useForm`.
  • You need to either set `defaultValue` at the field level or `useForm`'s `defaultValues`. If you used defaultValues at useForm, skip using this prop.
  • If your form will invoke `reset` with default values, you will need to provide `useForm` with `defaultValues`.
  • Calling `onChange` with `undefined` is not valid. You should use `null` or the empty string as your default/cleared value instead.
  • If `field.value` is `undefined` on first render, the input starts out uncontrolled and React will warn when it later becomes controlled — always set `defaultValue`/`defaultValues` to avoid this.
| | `exact` | `boolean = true` | | _(since v7.68.0)_ This prop will enable an exact match for input name subscriptions, default to true. _(since v7.81.0)_ With `exact: true`, the field is also updated when one of its ancestor paths is set, but not when a nested child path of its value changes. See [`useController`](https://react-hook-form.com/docs/usecontroller) for details. | ### Return --- The following table contains information about properties which `Controller` produces. | Object Name | Name | Type | Description | | -------------------------------------- | -------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `field` | `onChange` | `(value: any) => void` | A function which sends the input's value to the library.

_It should be assigned to the `onChange` prop of the input and the value should **not be `undefined`**._
This prop updates [formState](https://react-hook-form.com/docs/useform/formstate) and you should avoid manually invoking [setValue](https://react-hook-form.com/docs/useform/setvalue) or other APIs related to field updates. It accepts either a change event or a value: given an event, it reads `target.checked` for checkboxes, `target.files` for file inputs and `target.value` otherwise. Any object with a `target` property is treated as an event. | | `field` | `onBlur` | `() => void` | A function which sends the input's onBlur event to the library. It should be assigned to the input's `onBlur` prop. | | `field` | `value` | `unknown` | The current value of the controlled component. | | `field` | `disabled` | `boolean` | The disabled state of the input. | | `field` | `name` | `string` | Input's name being registered. | | `field` | `ref` | `React.Ref` | A ref used to connect hook form to the input. Assign `ref` to component's input ref to allow hook form to focus the error input — this only works if the target component forwards refs (`React.forwardRef`) or exposes an equivalent, like MUI's `inputRef`. | | `fieldState` | `invalid` | `boolean` | Invalid state for current input. | | `fieldState` | `isTouched` | `boolean` | Touched state for current controlled input. | | `fieldState` | `isDirty` | `boolean` | Dirty state for current controlled input. | | `fieldState` | `isValidating` | `boolean` | Validating state for current controlled input. | | `fieldState` | `error` | `object` | _(since v7.0.0)_ error for this specific input. | | [`formState`](https://react-hook-form.com/docs/useform/formstate) | `isDirty` | `boolean` | Set to `true` after the user modifies any of the inputs.
  1. **Important:** Make sure to provide all inputs' defaultValues at the useForm level, so the library can have a single source of truth to compare whether the form is dirty.
  2. File-type inputs will need to be managed at the app level due to the ability to cancel file selection and [FileList](https://developer.mozilla.org/en-US/docs/Web/API/FileList) object.
| | `formState` | `dirtyFields` | `object` | An object with the user-modified fields. Make sure to provide all inputs' defaultValues via useForm, so the library can compare against the `defaultValues`
  1. **Important:** Make sure to provide defaultValues at the useForm level, so the library can have a single source of truth to compare each field's dirtiness.
  2. Dirty fields will **not** represent as `isDirty` formState, because dirty fields are marked field dirty at the field level rather than the entire form. If you want to determine the entire form state use `isDirty` instead.
| | `formState` | `touchedFields` | `object` | An object containing all the inputs the user has interacted with. | | `formState` | `defaultValues` | `object` | _(since v7.37.0)_ The value that was set in [useForm](https://react-hook-form.com/docs/useform)'s `defaultValues` or updated `defaultValues` via the [reset](https://react-hook-form.com/docs/useform/reset) API. | | `formState` | `isSubmitted` | `boolean` | Set to `true` after the form has been submitted. Will remain `true` until the `reset` method is invoked. | | `formState` | `isSubmitSuccessful` | `boolean` | Indicates that the form was successfully submitted without any runtime error. | | `formState` | `isSubmitting` | `boolean` | `true` if the form is currently being submitted. `false` otherwise. | | `formState` | `isLoading` | `boolean` | _(since v7.41.0)_ `true` if the form is currently loading async default values.
**Important:** this prop is only applicable to async `defaultValues` | | `formState` | `submitCount` | `number` | The number of times the form was submitted. | | `formState` | `isValid` | `boolean` | Set to `true` if the form doesn't have any errors.

`setError` immediately forces `isValid` to `false`; this value is not itself derived from validation and will be overwritten the next time validation runs (e.g. on the next `onChange`, submit, or `trigger()` call). | | `formState` | `isValidating` | `boolean` | Set to `true` during validation. | | `formState` | `validatingFields` | `object` | _(since v7.51.0)_ Captures fields that are undergoing asynchronous validation. | | `formState` | `errors` | `object` | An object with field errors. There is also an [ErrorMessage](https://react-hook-form.com/docs/useformstate/errormessage) component to retrieve error messages easily. | | `formState` | `disabled` | `boolean` | _(since v7.48.0)_ Set to `true` if the form is disabled via the `disabled` prop in [`useForm`](https://react-hook-form.com/docs/useform#disabled). | | `formState` | `isReady` | `boolean` | _(since v7.56.0)_ Set to true when `formState` subscription setup is ready. | ### Examples --- **Web** **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) ```tsx import ReactDatePicker from "react-datepicker" import { useForm, Controller } from "react-hook-form" type FormValues = { ReactDatepicker: Date | null } export default function App() { const { handleSubmit, control } = useForm({ defaultValues: { ReactDatepicker: null }, }) return (
console.log(data))}> ( )} /> ) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-controller-5h1q5) ```javascript import ReactDatePicker from "react-datepicker" import { useForm, Controller } from "react-hook-form" export default function App() { const { handleSubmit, control } = useForm({ defaultValues: { ReactDatepicker: null }, }) return (
console.log(data))}> ( )} /> ) } ``` **React Native** [Open in Expo Snack](https://snack.expo.io/@bluebill1049/react-hook-form-v7---controller) ```javascript import { Text, View, TextInput, Button, Alert } from "react-native" import { useForm, Controller } from "react-hook-form" export default function App() { const { control, handleSubmit, formState: { errors }, } = useForm({ defaultValues: { firstName: "", lastName: "", }, }) const onSubmit = (data) => console.log(data) return ( ( )} name="firstName" /> {errors.firstName && This is required.} ( )} name="lastName" /> ))} ) } ``` **TS** [Open in CodeSandbox](https://codesandbox.io/s/calc-i231d) ```tsx import { useForm, useFieldArray, useWatch, Control } from "react-hook-form" type FormValues = { cart: { name: string price: number quantity: number }[] } const Total = ({ control }: { control: Control }) => { const formValues = useWatch({ name: "cart", control, }) const total = formValues.reduce( (acc, current) => acc + (current.price || 0) * (current.quantity || 0), 0 ) return

Total Amount: {total}

} export default function App() { const { register, control, handleSubmit, formState: { errors }, } = useForm({ defaultValues: { cart: [{ name: "test", quantity: 1, price: 23 }], }, mode: "onBlur", }) const { fields, append, remove } = useFieldArray({ name: "cart", control, }) const onSubmit = (data: FormValues) => console.log(data) return (
{fields.map((field, index) => { return (
) })}
) } ``` [Open in CodeSandbox](https://codesandbox.io/s/usefieldarray-with-preview-odmtx5) ```javascript import { useForm, useFieldArray, useWatch } from "react-hook-form" export default function App() { const { control, handleSubmit } = useForm() const { fields, append, update } = useFieldArray({ control, name: "array", }) return (
console.log(data))}> {fields.map((field, index) => ( ))} ) } const Display = ({ control, index }) => { const data = useWatch({ control, name: `array.${index}`, }) return

{data?.firstName}

} const Edit = ({ update, index, value, control }) => { const { register, handleSubmit } = useForm({ defaultValues: value, }) return (
) } ``` [Open in CodeSandbox](https://codesandbox.io/s/usefieldarray-conditional-2wi6f) ```javascript import { useForm, useWatch, useFieldArray, Control } from "react-hook-form" const ConditionField = ({ control, index, register }) => { const output = useWatch({ name: "data", control, defaultValue: "yay! I am watching you :)", }) return ( <> {output[index]?.name === "bill" && ( )} ) } const UseFieldArrayUnregister = () => { const { control, handleSubmit, register } = useForm({ defaultValues: { data: [{ name: "test" }, { name: "test1" }, { name: "test2" }], }, mode: "onSubmit", shouldUnregister: false, }) const { fields } = useFieldArray({ control, name: "data", }) const onSubmit = (data) => console.log(data) return (
{fields.map((data, index) => ( <> ))} ) } ``` ```tsx import { useForm, useFieldArray } from "react-hook-form" const App = () => { const { register, control } = useForm({ defaultValues: { test: [{ value: "1" }, { value: "2" }], }, }) const { fields, prepend, append } = useFieldArray({ name: "test", control, }) return (
{fields.map((field, i) => ( ))}
) } ``` ```tsx import { useForm, useFieldArray, Control, UseFormRegister, } from "react-hook-form" type FormValues = { teams: { name: string members: { email: string }[] }[] } function Members({ teamIndex, control, register, }: { teamIndex: number control: Control register: UseFormRegister }) { const { fields, append, remove } = useFieldArray({ control, name: `teams.${teamIndex}.members`, }) return (
    {fields.map((field, memberIndex) => (
  • ))}
) } export default function App() { const { control, register, handleSubmit } = useForm({ defaultValues: { teams: [{ name: "", members: [{ email: "" }] }], }, }) const { fields, append, remove } = useFieldArray({ control, name: "teams", }) return (
console.log(data))}> {fields.map((field, teamIndex) => (
))}
) } ``` ### Video --- [Watch on YouTube](https://www.youtube.com/watch?v=4MrbfGSFY2A) ### Tips --- **Custom Register** You can also `register` inputs at `Controller` without the actual input. This makes `useFieldArray` quick and flexible to use with complex data structures or the the actual data is not stored inside an input. [Open in CodeSandbox](https://codesandbox.io/s/usefieldarray-virtual-input-v9wyw) ```javascript import { useForm, useFieldArray, Controller, useWatch } from "react-hook-form" const ConditionalInput = ({ control, index, field }) => { const value = useWatch({ name: "test", control, }) return ( value?.[index]?.checkbox === "on" ? : null } /> ) } function App() { const { control, register } = useForm() const { fields, append, prepend } = useFieldArray({ control, name: "test", }) return (
{fields.map((field, index) => ( ))} ) } ``` **Controlled Field Array** There will be cases where you want to control the entire field array, which means each onChange reflects on the `fields` object. If you only need to display values from the array, such as a live total, read them with [`useWatch`](https://react-hook-form.com/docs/usewatch) (`useWatch({ control, name: "fieldArray" })`) in a child component instead, so only that component re-renders. [Open in CodeSandbox](https://codesandbox.io/s/infallible-bush-c92l0?file=/src/App.tsx) ```tsx import { useForm, useFieldArray } from "react-hook-form" export default function App() { const { register, handleSubmit, control, watch } = useForm() const { fields, append } = useFieldArray({ control, name: "fieldArray", }) const watchFieldArray = watch("fieldArray") const controlledFields = fields.map((field, index) => { return { ...field, ...watchFieldArray[index], } }) return (
{controlledFields.map((field, index) => { return ( ) })}
) } ``` ### Troubleshooting --- #### The field array is empty after data loads from an API **Why it happens:** `fields` is built from `defaultValues`, which `useForm` reads once on the first render. Rows in data that arrives later are ignored. **Fix:** Pass the data to [`values`](https://react-hook-form.com/docs/useform#values). The form updates whenever `values` changes: ```javascript const { data } = useQuery(...) const { control } = useForm({ values: data }) const { fields } = useFieldArray({ control, name: "items" }) ``` Or call [`reset(data)`](https://react-hook-form.com/docs/useform/reset) once the data arrives. #### My item's own `id` is replaced by a generated value **Why it happens:** Each entry in `fields` gets a generated key, stored in `field.id` by default, so React can track rows across `append`, `remove`, `move`, and other operations. If your objects already have an `id` property (for example, database records), the generated key shadows it in `fields`. The generated key exists only in `fields`. It is not written to your form values, so `getValues()` and the data passed to `handleSubmit` keep your original `id`. **Fix:** Set [`keyName`](#props) so the generated key uses a different property: ```javascript const { fields } = useFieldArray({ control, name: "items", keyName: "key" }) return fields.map((field, index) => (
{field.id} {/* your record's id */}
)) ``` Or keep the default and read your own `id` from form values with ``getValues(`items.${index}.id`)``. --- # FieldArray > React Hook Form's FieldArray component wraps useFieldArray in a render prop, so you can append, remove, and manage dynamic form fields declaratively. Source: https://react-hook-form.com/docs/usefieldarray/fieldarray ## `FieldArray:` [FieldArrayProps](https://react-hook-form.com/ts#FieldArrayProps) _(since v7.81.0)_ Component based on the [`useFieldArray`](https://react-hook-form.com/docs/usefieldarray) hook, useful for working with dynamic field arrays as a headless/controlled component. All props are the same as `useFieldArray`, plus a `render` prop that receives the hook's return value. ```javascript fields.map((field, index) => ( )) } /> ``` ### Props --- | Name | Type | Required | Description | | ------------------ | ---------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `render` | `Function` | ✓ | Render prop function that receives the same object [`useFieldArray`](https://react-hook-form.com/docs/usefieldarray#return) returns (`fields`, `append`, `prepend`, `insert`, `remove`, `swap`, `move`, `update`, `replace`) and returns a React element. | | `name` | `string` | ✓ | Name of the field array. **Note:** Dynamic names are not supported. | | `control` | `Object` | | [`control`](https://react-hook-form.com/docs/useform/control) object provided by `useForm`. It's optional if you are using `FormProvider`. | | `shouldUnregister` | `boolean` | | Whether Field Array will be unregistered after unmount. | | `disabled` | `boolean` | | Disables the entire field array. When `true`, `fields` remains populated but every entry's `disabled` property is set to `true`, all mutation methods (`append`, `prepend`, `insert`, `remove`, `swap`, `move`, `update`, `replace`) become no-ops, and the array's internal subscriptions are not set up. Useful for conditionally enabling a field array in discriminated union form shapes. | | `keyName` | `string = "id"` | | Name of the attribute with autogenerated identifier to use as the `key` prop. This prop is no longer required and is removed in v8, where rows always use `key` (see [v8 migration notes](https://react-hook-form.com/migrate-v7-to-v8#useFieldArray)). | | `rules` | `Object` | | The same validation `rules` API as for [`register`](https://react-hook-form.com/docs/useform/register), which includes: `required`, `minLength`, `maxLength`, `validate`. In case of validation error, the `root` property is appended to `formState.errors?.?.root` (e.g. `formState.errors?.test?.root` for a field array named `test`), of type [`FieldError`](https://react-hook-form.com/ts#FieldError). **Important:** This is only applicable to **built-in** validation. | ### Return --- The following table contains information about the object passed to the `render` prop function — it's identical to what [`useFieldArray`](https://react-hook-form.com/docs/usefieldarray#return) returns. | Name | Type | Description | | --------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `fields` | `object & \{ id: string \}` | This `object` contains the `defaultValue` and `id` for your component. When the hook-level `disabled` prop is set, every entry's `disabled` property reflects it — but this is not automatically forwarded to the registered input; you need to spread it onto the input yourself. | | `append` | `(obj: object \| object[], focusOptions) => void` | Append input/inputs to the end of your fields and focus. The input value will be registered during this action. **Important:** append data is required and not partial. | | `prepend` | `(obj: object \| object[], focusOptions) => void` | Prepend input/inputs to the start of your fields and focus. The input value will be registered during this action. **Important:** prepend data is required and not partial. | | `insert` | `(index: number, value: object \| object[], focusOptions) => void` | Insert input/inputs at particular position and focus. **Important:** insert data is required and not partial. | | `swap` | `(from: number, to: number) => void` | Swap input/inputs position. | | `move` | `(from: number, to: number) => void` | Move input/inputs to another position. | | `update` | `(index: number, obj: object) => void` | Update input/inputs at a particular position, updated fields will get unmounted and remounted. If this is not desired behavior, please use [`setValue`](https://react-hook-form.com/docs/useform/setvalue) API instead. **Important:** update data is required and not partial. | | `replace` | `(obj: object[]) => void` | Replace the entire field array values. | | `remove` | `(index?: number \| number[]) => void` | Remove input/inputs at particular position, or remove all when no index provided. | > **Important: Rules** > > - The same rules that apply to [`useFieldArray`](https://react-hook-form.com/docs/usefieldarray#rules) apply here — `field.id` (not `index`) must be used as the component `key`, and `shouldUnregister: true` is not supported. In v8, use `field.key` instead of `field.id`. > - `render` is called on every render, so keep it free of side effects. > ### Examples --- ```tsx import { useForm, FieldArray } from "react-hook-form" type FormValues = { test: { value: string }[] } export default function App() { const { control, register, handleSubmit } = useForm({ defaultValues: { test: [{ value: "" }], }, }) return (
console.log(data))}> ( <> {fields.map((field, index) => (
))} )} /> ) } ``` ### Tips --- - Use `FieldArray` when you cannot call a hook, for example when a field array is rendered conditionally or inside a loop. Hooks cannot be called conditionally, but components can be rendered conditionally. - For nested arrays, render a `FieldArray` inside another one's `render`, and build the name from the parent index: ```javascript fields.map((section, index) => ( ( )} /> )) } /> ``` - Errors from `rules` are stored at `errors..root`, for example `errors.sections?.root?.message`. Show them next to the list, not next to one row. ### Troubleshooting --- #### Rows show the wrong values after removing or moving an item **Why it happens:** The rendered rows use the array index as their React key. After an item moves, React reuses the DOM for a different field, so inputs and their form state no longer line up. **Fix:** Use the generated field identifier as the key: ```javascript fields.map((field, index) => ( )) ``` In v8, use `field.key` instead of `field.id`. #### A newly appended row has missing or uncontrolled fields **Why it happens:** `append`, `prepend`, `insert`, and `update` require complete row objects. Passing `{}` or a partial object leaves fields without initial values. **Fix:** Pass every field in the row, including empty defaults: ```javascript append({ name: "", quantity: 1 }) ``` Use [`setValue`](https://react-hook-form.com/docs/useform/setvalue) when you only need to change one property of an existing row. --- # useForm > The primary React Hook Form hook. Initialize your form with validation rules, default values, and submission handling in a single call. Source: https://react-hook-form.com/docs/useform ## `useForm:` [`UseFormProps`](https://react-hook-form.com/ts#UseFormProps) `useForm` is a custom hook for managing forms with ease. It takes one object as an **optional** argument. The following example demonstrates all of its properties along with their default values. **Generic props:** | Option | Description | | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [mode](#mode) | Validation strategy for **before** submission behavior. | | [reValidateMode](#reValidateMode) | Validation strategy for **after** submission behavior. | | [defaultValues](#defaultValues) | Default values for the form; this value will be cached. | | [values](#values) | Reactive values to update the form values. | | [errors](#errors) | Server returns errors to update form. **⚠ Important:** Keep the errors object reference-stable to avoid infinite re-renders. | | [resetOptions](#resetOptions) | Option to reset form state when updating with new form values. | | [criteriaMode](#criteriaMode) | Display all validation errors or one at a time. | | [shouldFocusError](#shouldFocusError) | Enable or disable built-in focus management. | | [delayError](#delayError) | Delay error from appearing instantly. | | [validate](#validate) | Form-level validation is limited to built-in validation methods. | | [shouldUseNativeValidation](#shouldUseNativeValidation) | Use browser built-in form constraint API. | | [shouldUnregister](#shouldUnregister) | Enable and disable input unregister after unmount. | | [progressive](#progressive) | Forward validation attributes (`required`, `min`, `max`, etc.) as native HTML attributes on inputs. Enables progressive enhancement for the `Form` component (usable HTML before hydration/JS loads). | | [disabled](#disabled) | Disable the entire form with all associated inputs. | | [formControl](https://react-hook-form.com/docs/createFormControl) | Supply a pre-created form control object (from `createFormControl`) instead of letting `useForm` create one internally. | **Schema validation props:** | Option | Description | | --------------------- | --------------------------------------------------------- | | [resolver](#resolver) | Integrates with your preferred schema validation library. | | [context](#context) | A context object to supply for your schema validation. | ### Props --- #### mode: `onChange | onBlur | onSubmit | onTouched | all = 'onSubmit'` (React Native: compatible with Controller) --- This option allows you to configure the validation strategy for before a user submits the form. Validation occurs during the `onSubmit` event, which is triggered by invoking the [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit) function. | Name | Type | Description | | --------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | onSubmit | `string` | Validation is triggered on the `submit` event, and inputs attach `onChange` event listeners to re-validate themselves. | | onBlur | `string` | Validation is triggered on the `blur` event. | | onChange | `string` | Validation is triggered on the `change` event for each input, leading to multiple re-renders. Warning: this often comes with a significant impact on performance. | | onTouched | `string` | Validation is initially triggered on the first `blur` event. After that, it is triggered on every `change` event.

**Note:** when using with `Controller`, make sure to wire up `onBlur` with the `render` prop. | | all | `string` | Validation is triggered on both `blur` and `change` events. | #### reValidateMode: `onChange | onBlur | onSubmit = 'onChange'` (React Native: Custom register or using Controller) --- This option allows you to configure the validation strategy for when inputs with errors get re-validated **after** a user submits the form (the `onSubmit` event occurs and the [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit) function is executed). By default, re-validation occurs during the input change event. **Note:** _(since v7.56.0)_ Both `mode` and `reValidateMode` are reactive — you can update them after form initialization and the new strategy will take effect on subsequent validations. #### defaultValues: `FieldValues | () => Promise` --- The `defaultValues` prop populates the entire form with default values. It supports both synchronous and asynchronous assignment of default values. While you can set an input's default value using `defaultValue` or `defaultChecked` [(as detailed in the official React documentation)](https://react.dev/reference/react-dom/components/input), it is **recommended** to use `defaultValues` for the entire form. ```javascript useForm({ defaultValues: { firstName: "", lastName: "", }, }) // set default value async useForm({ defaultValues: async () => fetch("/api-endpoint").then((res) => res.json()), }) ``` > **Important: Rules** > > - You **should avoid** providing `undefined` as a default value, as it conflicts with the default state of a controlled component. > - `defaultValues` are cached. To reset them, use the [reset](https://react-hook-form.com/docs/useform/reset) API. > - An async `defaultValues` function runs once, when the form mounts. If its promise rejects, `formState.isLoading` stays `true`, so catch errors inside the function and return fallback values: > > ```javascript > useForm({ > defaultValues: async () => { > try { > const res = await fetch("/api/user") > return await res.json() > } catch { > return { firstName: "", lastName: "" } > } > }, > }) > ``` > > - `defaultValues` will be included in the submission result by default. > - It's recommended to avoid using custom objects containing prototype methods, such as `Moment` or `Luxon`, as `defaultValues`. > - There are other options for including form data: > > ```javascript > // adding a hidden input > > ``` > > ```javascript > // include data onSubmit > const onSubmit = (data) => { > const output = { > ...data, > others: "others", > } > } > ``` > #### values: `FieldValues` _(since v7.41.0)_ --- The `values` prop will react to changes and update the form values, which is useful when your form needs to be updated by external state or server data. The `values` prop will overwrite the `defaultValues` prop, unless `resetOptions: { keepDefaultValues: true }` is also set for `useForm`. ```javascript // set default value sync function App({ values }) { useForm({ values, // will get updated when values props updates }) } function App() { const values = useFetch("/api") useForm({ defaultValues: { firstName: "", lastName: "", }, values, // will get updated once values returns }) } ``` > **Important: Rules** > > - `values` is deep-compared with the previous `values` prop. When it changes, the form is reset with the new values, which **replaces anything the user has typed**. If your data source refetches in the background (for example, React Query on window focus) and returns updated data, set `resetOptions: { keepDirtyValues: true }` to keep the user's edits. > - Passing a new object with the same content does nothing, so you don't need to memoize `values`. > ##### Loading form data from a server: which option to use? | Approach | Updates when the data changes | Good for | | --------------------------------------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | Async [`defaultValues`](#defaultValues) | No, it runs once on mount | Edit forms that load their data once. `formState.isLoading` is `true` until it resolves. | | [`values`](#values) | Yes, it resets the form whenever the data changes | Forms that must stay in sync with external or server state. Combine with [`resetOptions`](#resetOptions) to keep user edits. | | [`reset`](https://react-hook-form.com/docs/useform/reset) in `useEffect` | Only when your effect runs | Full control over when the form is refilled and which state to keep. | | Render the form after the data arrives | No | The simplest option: fetch in the parent and pass the data in as `defaultValues`. | #### errors: `FieldErrors` _(since v7.49.0)_ --- The `errors` prop will react to changes and update the server errors state, which is useful when your form needs to be updated with errors returned from the server. ```javascript function App() { const { errors, data } = useFetch("/api") useForm({ errors, // will get updated once errors returns }) } ``` #### resetOptions: [KeepStateOptions](https://react-hook-form.com/ts#KeepStateOptions) _(since v7.41.0)_ --- This property is related to value update behaviors. When `values` or `defaultValues` are updated, the `reset` API is invoked internally. It's important to specify the desired behavior after `values` or `defaultValues` are asynchronously updated. The configuration option itself is a reference to the [reset](https://react-hook-form.com/docs/useform/reset) method's options. ```javascript // by default, an asynchronous update to values or defaultValues will reset the form values useForm({ values }) useForm({ defaultValues: async () => await fetch() }) // options to configure the behavior // eg: I want to keep user-interacted/dirty values and not remove any user errors useForm({ values, resetOptions: { keepDirtyValues: true, // user-interacted input will be retained keepErrors: true, // input errors will be retained with value update }, }) ``` #### context: `object` --- | | | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | This context `object` is mutable and will be injected into the `resolver`'s second argument or [Yup](https://github.com/jquense/yup) validation's context object. | [CodeSandbox](https://codesandbox.io/s/resolver-context-d9jqy) | #### criteriaMode: `firstError | all` --- | | | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | |
  • When set to `firstError` (default), only the first error from each field will be gathered.
  • When set to `all`, all errors from each field will be gathered.
| [CodeSandbox](https://codesandbox.io/s/react-hook-form-v6-errors-validatecriteriamode-all-p9xm6) | #### shouldFocusError: `boolean = true` --- When set to `true` (default), and the user submits a form that fails validation, focus is set on the first field with an error. > **note** > > - Only works when the field's `ref` is actually attached to a DOM element — e.g. ``. A custom-registered input whose returned props are never spread onto a real element (so no `ref` is attached) won't receive focus, since there's nothing to focus. > - The focus order is based on the `register` order. > #### delayError: `number` _(since v7.12.0)_ --- | | | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | This configuration delays the display of error states to the end user by a specified number of milliseconds. If the user corrects the input with errors, the error is removed instantly, and the delay is not applied. | [CodeSandbox](https://codesandbox.io/s/useform-delayerror-q6c2d) | #### validate: `Function` _(since v7.72.0)_ --- This example demonstrates how to use the **new `validate` API** in combination with `useForm` to perform **form-level validation** in a React application. The `validate` function receives `{ formValues, formState, eventType, name }` and must return one of: `true` (valid), a `string` (surfaced at `formState.errors.form`), or an object of `{ [fieldName]: { type, message } }` (each entry surfaced at `formState.errors.form.`). **Note:** `validate` does not run when a `resolver` is configured — `resolver` and `validate` are mutually exclusive, and only `resolver` runs if both are set. ##### Examples --- ```javascript const { register, formState: { errors }, } = useForm({ validate: async ({ formValues }) => { if (formValues.test1.length > formValues.test.length) { return { test: { type: "formError", message: "something is wrong here", }, } } if (formValues.test === "test") { return "direct error message" } return true }, }) ``` #### shouldUnregister: `boolean = false` --- By default, an input value will be retained when an input is removed. However, you can set `shouldUnregister` to `true` to `unregister` the input during unmount. - This is a global configuration that overrides child-level configurations. To have individual behavior, set the configuration at the component or hook level, not at `useForm`. - By default, `shouldUnregister: false` means unmounted fields are **not validated** by built-in validation. - By setting `shouldUnregister` to true at `useForm` level, `defaultValues` will **not** be merged against submission result. - Setting `shouldUnregister: true` makes your form behave more closely to native forms. - Form values are stored within the inputs themselves. - Unmounting an input removes its value. - Hidden inputs should use the `hidden` attribute for storing hidden data. - Only registered inputs are included as submission data. - Unmounted inputs must be notified at either `useForm` or `useWatch`'s `useEffect` for the hook form to verify that the input is unmounted from the DOM. ```javascript const NotWork = ({ register, show }) => { // ❌ won't get notified; you need to invoke unregister return show && } const Work = ({ control, register }) => { // "show" is itself a registered checkbox field in the same form const { show } = useWatch({ control }) // ✅ gets notified in useEffect return show && } const App = () => { const [showNotWork, setShowNotWork] = useState(false) const { register, control } = useForm({ shouldUnregister: true }) return (
{/* ✅ gets notified in useForm's useEffect */} {showNotWork && }
) } ``` #### shouldUseNativeValidation: `boolean = false` _(since v7.9.0)_ --- This config will enable [browser native validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation). It will also enable CSS selectors `:valid` and `:invalid`, making input styling easier. You can still use these selectors even when client-side validation is disabled. - Only works with `onSubmit` and `onChange` modes, as the `reportValidity` execution will focus the error input. - Each registered field's validation message must be a string to be displayed natively. - This feature only works with the `register` API and  `useController/Controller` that are connected with actual DOM references. - `shouldUseNativeValidation` works independently of `progressive` — it drives the browser's Constraint Validation API (`setCustomValidity`/`reportValidity`) directly from React Hook Form's own computed validation results, regardless of whether validation attributes are forwarded as native HTML attributes. Pair it with [`progressive`](#progressive) if you also want the constraint attributes themselves (`required`, `minLength`, etc.) present on the DOM, e.g. for SSR or pre-hydration fallback validation. ```javascript useForm({ shouldUseNativeValidation: true, }) ``` ##### Examples --- ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit } = useForm({ shouldUseNativeValidation: true, progressive: true, }) const onSubmit = async (data) => { console.log(data) } return (
) } ``` #### progressive: `boolean = false` _(since v7.44.0)_ --- Forwards validation rules (`required`, `min`, `max`, `minLength`, `maxLength`, `pattern`) from [`register`](https://react-hook-form.com/docs/useform/register) as native HTML attributes on the input. Enables progressive enhancement for the [`Form`](https://react-hook-form.com/docs/useform/form) component (rendering usable HTML before hydration). Independent of [`shouldUseNativeValidation`](#shouldUseNativeValidation), which drives the browser's Constraint Validation API from React Hook Form's own validation results regardless of this option — pair the two if you also want the constraint attributes present on the DOM. ```javascript useForm({ progressive: true, }) ``` #### disabled: `boolean = false` _(since v7.48.0)_ --- This config allows you to disable the entire form and all associated inputs when set to `true`.
This can be useful for preventing user interaction during asynchronous tasks or other situations where inputs should be temporarily unresponsive. ##### Examples --- ```javascript import { useForm, Controller } from "react-hook-form" const App = () => { const [disabled, setDisabled] = useState(false) const { register, handleSubmit, control } = useForm({ disabled, }) return (
{ setDisabled(true) await sleep(100) setDisabled(false) })} > } name="test" />
) } ``` #### resolver: [Resolver](https://react-hook-form.com/ts#Resolver) --- This function allows you to use any external validation library such as [Yup](https://github.com/jquense/yup), [Zod](https://github.com/vriad/zod), [Joi](https://github.com/hapijs/joi), [Vest](https://github.com/ealush/vest), [Ajv](https://github.com/ajv-validator/ajv) and many others. The goal is to make sure you can seamlessly integrate whichever validation library you prefer. If you're not using a library, you can always write your own logic to validate your forms. ```bash npm install @hookform/resolvers ``` ##### Props --- | Name | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `values` | `object` | This object contains the entire form values. | | `context` | `object` | This is the `context` object which you can provide to the `useForm` config. It is a mutable `object` that can be changed on each re-render. | | `options` |
{JSON.stringify({ criteriaMode: "string", fields: "object", names: "string[]" }, null,2)}
| This is the options object containing information about the validated fields, names and `criteriaMode` from `useForm`. | > **Important: Rules** > > - Schema validation focuses on field-level error reporting. Parent-level error checking is limited to the direct parent level, which is applicable for components such as group checkboxes. > - This function will be cached. > - Re-validation of an input will only occur one field at a time during a user’s interaction. The library itself will evaluate the `error` object to trigger re-renders accordingly. > - A resolver cannot be used with the built-in validators (e.g.: required, min, etc.) > - When building a custom resolver: > - Make sure that you return an object with both `values` and `errors` properties. Their default values should be an empty object. For example: `{}`. > - The keys of the `errors` object should match the `name` values of your fields, but they _must_ be hierarchical rather than a single key for deep errors: > `❌ { "participants.1.name": someErr }` will not set or clear properly - instead, use `✅ { participants: [null, { name: someErr } ] }` as this is reachable > as `errors.participants[1].name` - you can still prepare your errors using flat keys, and then use a function like this one from the zod resolver: > [toNestErrors(flatErrs, resolverOptions)](https://github.com/react-hook-form/resolvers/blob/master/src/toNestErrors.ts) > ##### Examples --- **Yup** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-apply-validation-ts-forked-nmbyh) ```tsx import { useForm } from "react-hook-form" import { yupResolver } from "@hookform/resolvers/yup" import * as yup from "yup" const schema = yup .object() .shape({ name: yup.string().required(), age: yup.number().required(), }) .required() const App = () => { const { register, handleSubmit } = useForm({ resolver: yupResolver(schema), // yup, joi and even your own. }) return (
console.log(d))}>
) } ``` **Zod** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-zod-resolver-ts-example-forked-w72vp) ```tsx import { useForm } from "react-hook-form" import { zodResolver } from "@hookform/resolvers/zod" import * as z from "zod" const schema = z.object({ name: z.string(), age: z.number(), }) type Schema = z.infer const App = () => { const { register, handleSubmit } = useForm({ resolver: zodResolver(schema), }) return (
{ // handle inputs console.log(data) })} >
) } ``` **Joi** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-joiresolver-v6-ts-forked-5pseh) ```tsx import { useForm } from "react-hook-form" import { joiResolver } from "@hookform/resolvers/joi" import Joi from "joi" interface IFormInput { name: string age: number } const schema = Joi.object({ name: Joi.string().required(), age: Joi.number().required(), }) const App = () => { const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: joiResolver(schema), }) const onSubmit = (data: IFormInput) => { console.log(data) } return (
) } ``` **Ajv** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-ajvresolver-vr3imc) ```tsx import { useForm } from "react-hook-form" import { ajvResolver } from "@hookform/resolvers/ajv" // must use `minLength: 1` to implement required field const schema = { type: "object", properties: { username: { type: "string", minLength: 1, errorMessage: { minLength: "username field is required" }, }, password: { type: "string", minLength: 1, errorMessage: { minLength: "password field is required" }, }, }, required: ["username", "password"], additionalProperties: false, } const App = () => { const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: ajvResolver(schema), }) return (
console.log(data))}> {errors.username &&

{errors.username.message}

} {errors.password &&

{errors.password.message}

}
) } ``` **Vest** [Open in CodeSandbox](https://codesandbox.io/s/vest-8q874) ```tsx import { useForm } from "react-hook-form" import { vestResolver } from "@hookform/resolvers/vest" import vest, { test, enforce } from "vest" const validationSuite = vest.create((data = {}) => { test("username", "Username is required", () => { enforce(data.username).isNotEmpty() }) test("username", "Must be longer than 3 chars", () => { enforce(data.username).longerThan(3) }) test("password", "Password is required", () => { enforce(data.password).isNotEmpty() }) test("password", "Password must be at least 5 chars", () => { enforce(data.password).longerThanOrEquals(5) }) test("password", "Password must contain a digit", () => { enforce(data.password).matches(/[0-9]/) }) test("password", "Password must contain a symbol", () => { enforce(data.password).matches(/[^A-Za-z0-9]/) }) }) const App = () => { const { register, handleSubmit } = useForm({ resolver: vestResolver(validationSuite), }) return (
console.log(data))}>
) } ``` **Custom** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-customresoliver-ts-v7-juc63) ```tsx import { useForm } from "react-hook-form" import * as Joi from "joi" interface IFormInputs { username: string } const validationSchema = Joi.object({ username: Joi.string().alphanum().min(3).max(30).required(), }) const App = () => { const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: async (data) => { const { error, value: values } = validationSchema.validate(data, { abortEarly: false, }) return { values: error ? {} : values, errors: error ? error.details.reduce((previous, currentError) => { return { ...previous, [currentError.path[0]]: currentError, } }, {}) : {}, } }, }) const onSubmit = (data: IFormInputs) => console.log(data) return (

resolver

{errors.username &&

{errors.username.message}

}
) } ``` Need more? See [Resolver Documentation](https://github.com/react-hook-form/resolvers#quickstart) > **Tip** > > You can debug your schema via the following code snippet: > > ```javascript > resolver: async (data, context, options) => { > // you can debug your validation schema here > console.log("formData", data) > console.log( > "validation result", > await anyResolver(schema)(data, context, options) > ) > return anyResolver(schema)(data, context, options) > } > ``` > #### `useForm` return and `useEffect` dependencies In a future major release, the `useForm` return value will be memoized to optimize performance and reflect changes in the `formState`. Once that ships, the returned object will get a new reference whenever `formState` updates — so depending on it directly in a `useEffect` dependency array will re-run that effect on every `formState` change, which can create an infinite loop if the effect itself updates the form (e.g. calling `reset`). > **Warning** > > Avoid depending on the entire `useForm` return value going forward — the following pattern will break once memoization ships: > > ```javascript > const methods = useForm() > > useEffect(() => { > methods.reset({ ... }) > }, [methods]) > ``` > Passing only the relevant methods, as shown below, should avoid this kind of issue: ```javascript const methods = useForm() useEffect(() => { methods.reset({ ... }) }, [methods.reset]) ``` > **Tip** > > The recommended way is to pass destructured methods to the dependencies of a `useEffect` > > ```javascript > const { reset } = useForm() > > useEffect(() => { > reset({ ... }) > }, [reset]) > ``` > [More info can be found on this issue](https://github.com/react-hook-form/react-hook-form/issues/12463) #### Return --- The following list contains references to `useForm` return props. - [register](https://react-hook-form.com/docs/useform/register) - [unregister](https://react-hook-form.com/docs/useform/unregister) - [formState](https://react-hook-form.com/docs/useform/formstate) - [watch](https://react-hook-form.com/docs/useform/watch) - [subscribe](https://react-hook-form.com/docs/useform/subscribe) - [handleSubmit](https://react-hook-form.com/docs/useform/handlesubmit) - [reset](https://react-hook-form.com/docs/useform/reset) - [resetField](https://react-hook-form.com/docs/useform/resetfield) - [resetDefaultValues](https://react-hook-form.com/docs/useform/resetdefaultvalues) - [setError](https://react-hook-form.com/docs/useform/seterror) - [clearErrors](https://react-hook-form.com/docs/useform/clearerrors) - [setValue](https://react-hook-form.com/docs/useform/setvalue) - [setValues](https://react-hook-form.com/docs/useform/setvalues) - [setFocus](https://react-hook-form.com/docs/useform/setfocus) - [getValues](https://react-hook-form.com/docs/useform/getvalues) - [getErrors](https://react-hook-form.com/docs/useform/geterrors) - [getFieldState](https://react-hook-form.com/docs/useform/getfieldstate) - [trigger](https://react-hook-form.com/docs/useform/trigger) - [control](https://react-hook-form.com/docs/useform/control) - [Form](https://react-hook-form.com/docs/useform/form) ### Examples --- A complete sign-up form: default values, validation rules, error messages, and an async submit that disables the button while it runs. **TS** ```tsx import { useForm } from "react-hook-form" type FormValues = { email: string password: string } export default function App() { const { register, handleSubmit, formState: { errors, isSubmitting }, } = useForm({ defaultValues: { email: "", password: "" }, mode: "onTouched", }) const onSubmit = async (data: FormValues) => { await fetch("/api/sign-up", { method: "POST", body: JSON.stringify(data), }) } return (
{errors.email &&

{errors.email.message}

} {errors.password &&

{errors.password.message}

}
) } ``` **JS** ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit, formState: { errors, isSubmitting }, } = useForm({ defaultValues: { email: "", password: "" }, mode: "onTouched", }) const onSubmit = async (data) => { await fetch("/api/sign-up", { method: "POST", body: JSON.stringify(data), }) } return (
{errors.email &&

{errors.email.message}

} {errors.password &&

{errors.password.message}

}
) } ``` ### Tips --- - Give every field a default value in `defaultValues`, even if it is just `""`. `isDirty`, `dirtyFields`, `reset`, and controlled components all compare against `defaultValues`, so a missing default can make a field look dirty or switch from uncontrolled to controlled. - If you are not sure which `mode` to use, try `mode: "onTouched"`. Errors show after the user leaves a field, and then update on every change. Users are not shown errors while they are still typing for the first time. - To load data from an API, pass it to [`values`](#values) instead of calling `reset` in a `useEffect`. The form updates when the values change, and the values are compared deeply, so a new object with the same content does not reset the form. - In a large form, keep `useForm` in the parent and move the parts that change often into child components. Read values with [`useWatch`](https://react-hook-form.com/docs/usewatch) and state with [`useFormState`](https://react-hook-form.com/docs/useformstate) in those children, so the whole form does not re-render on every key press. ### Troubleshooting --- #### Fields stay empty after data loads from an API **Why it happens:** `defaultValues` is read once, on the first render, and then cached. If the data arrives later, the new `defaultValues` object is ignored. **Fix:** Pass the data to [`values`](https://react-hook-form.com/docs/useform#values). The form updates whenever `values` changes: ```javascript const { data } = useQuery(...) const { register } = useForm({ values: data }) ``` Or call [`reset(data)`](https://react-hook-form.com/docs/useform/reset) once the data arrives. #### Errors only appear after the first submit **Why it happens:** This is the default. With `mode: "onSubmit"`, fields are not validated until the form is submitted. After that, `reValidateMode` (`"onChange"` by default) re-checks them as the user types. **Fix:** Set [`mode`](#mode) to validate earlier, for example `useForm({ mode: "onTouched" })` to show errors when the user leaves a field. #### `formState.isValid` (or another value) is always `false` in an event handler **Why it happens:** `formState` only tracks the values your component reads during render. If you read `formState.isValid` only inside a click handler or effect, the form never subscribed to it, so it is not kept up to date. **Fix:** Read the value during render, for example by destructuring it: ```javascript const { formState: { isValid }, } = useForm({ mode: "onChange" }) ``` --- # clearErrors > Manually clear validation errors for one field, an array of fields, or the entire React Hook Form without triggering re-validation. Source: https://react-hook-form.com/docs/useform/clearerrors ## `clearErrors:` [UseFormClearErrors](https://react-hook-form.com/ts#UseFormClearErrors) This function can manually clear errors in the form. ### Props --- | Type | Description | Example | | ------------------------------ | ----------------------- | --------------------------------------- | | `undefined` | Remove all errors. | `clearErrors()` | | `string` | Remove single error. | `clearErrors("yourDetails.firstName")` | | `string[]` | Remove multiple errors. | `clearErrors(["yourDetails.lastName"])` | - `undefined`: reset all errors - `string`: reset the error on a single field or by key name. ```javascript register("test.firstName", { required: true }) register("test.lastName", { required: true }) clearErrors("test") // will clear both errors from test.firstName and test.lastName clearErrors("test.firstName") // for clear single input error ``` - `string[]`: reset errors on the given fields > **Important: Rules** > > - This method does not affect the validation rules attached to inputs and does not > impact formState.isValid. > ### Examples --- **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-ts-clearerrors-w3ymx) ```tsx import { useForm } from "react-hook-form" type FormInputs = { firstName: string lastName: string username: string } const App = () => { const { register, formState: { errors }, handleSubmit, clearErrors, } = useForm() const onSubmit = (data: FormInputs) => { console.log(data) } return (
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-clearerrors-w5tl6) ```javascript import { useForm } from "react-hook-form" const App = () => { const { register, formState: { errors }, handleSubmit, clearErrors, } = useForm() const onSubmit = (data) => console.log(data) return (
) } ``` ### Tips --- - Clear a server error as soon as the user starts to fix it: ```javascript clearErrors("root.server"), })} /> ``` - `clearErrors("root")` clears every root error, for example `root.server` and `root.network`, because it removes everything under that path. - `clearErrors` does not re-validate. If a field is still invalid, its error comes back the next time validation runs. To check a field again right away, use [`trigger`](https://react-hook-form.com/docs/useform/trigger). ### Troubleshooting --- #### The error comes back after calling `clearErrors` **Why it happens:** `clearErrors` removes the stored error, but it does not change the field value or its validation rules. The next blur, change, or submit validates the same invalid value and creates the error again. **Fix:** Correct the value before clearing the error, or change the validation rule. To immediately check the current value again, call [`trigger("fieldName")`](https://react-hook-form.com/docs/useform/trigger) instead of clearing the error. #### `isValid` stays `false` after all errors are cleared **Why it happens:** `isValid` is derived from validation, not from whether the `errors` object was manually emptied. Calling `clearErrors` does not run validation or make an invalid form valid. **Fix:** Fix the invalid values and call [`trigger()`](https://react-hook-form.com/docs/useform/trigger) if you need to recompute validity immediately. --- # control > The control object returned by useForm, required to register controlled inputs via the Controller component and useController hook. Source: https://react-hook-form.com/docs/useform/control ## `control:` [Control](https://react-hook-form.com/ts#Control) This object contains methods for registering components into React Hook Form. Pass it to [`Controller`](https://react-hook-form.com/docs/usecontroller/controller), [`useController`](https://react-hook-form.com/docs/usecontroller), [`useWatch`](https://react-hook-form.com/docs/usewatch), [`useFieldArray`](https://react-hook-form.com/docs/usefieldarray), [`useFormState`](https://react-hook-form.com/docs/useformstate), or [`FormProvider`](https://react-hook-form.com/docs/formprovider) so those APIs can connect to the same form instance — it's optional wherever the component is already inside a `FormProvider`. > **Important: Rules** > > **Important:** do not access any of the properties inside this object directly; it is for internal use only. > ### Examples --- A complete form where a reusable input component receives `control` as a prop. The parent owns the form; the child only connects to it. **TS** ```tsx import { useForm, useController, type Control, type FieldPath, type FieldValues, } from "react-hook-form" type FormValues = { firstName: string email: string } type TextInputProps = { control: Control name: FieldPath label: string } function TextInput({ control, name, label, }: TextInputProps) { const { field, fieldState } = useController({ control, name, rules: { required: `${label} is required` }, }) return ( ) } export default function App() { const { control, handleSubmit } = useForm({ defaultValues: { firstName: "", email: "" }, }) const onSubmit = (data: FormValues) => console.log(data) return (
) } ``` **JS** ```javascript import { useForm, useController } from "react-hook-form" function TextInput({ control, name, label }) { const { field, fieldState } = useController({ control, name, rules: { required: `${label} is required` }, }) return ( ) } export default function App() { const { control, handleSubmit } = useForm({ defaultValues: { firstName: "", email: "" }, }) const onSubmit = (data) => console.log(data) return (
) } ``` ### Tips --- - Think of `control` as an internal object that you only pass along. Give it to the APIs listed above, and do not read its properties or call its methods yourself. They are not part of the public API and can change in any release. - Inside a [`FormProvider`](https://react-hook-form.com/docs/formprovider), you usually do not need `control` at all. Hooks such as [`useController`](https://react-hook-form.com/docs/usecontroller), [`useWatch`](https://react-hook-form.com/docs/usewatch), and [`useFormState`](https://react-hook-form.com/docs/useformstate) read it from context. - If you pass `control` as a prop, type it as `Control`, or make the component generic to reuse it across forms. See [the TypeScript error below](#TypeControlFormValuesisnotassignabletotypeControlFieldValues) if the types don't line up. ### Troubleshooting --- #### `Cannot read properties of null (reading '_names')` **Why it happens:** `useController` or `Controller` could not find a form. The component is rendered outside a [`FormProvider`](https://react-hook-form.com/docs/formprovider) and no `control` prop was passed. Hooks such as `useWatch` fail the same way, with a different property name in the message. **Fix:** Pass `control` from `useForm`, or wrap the tree in ``. #### A field is missing from the submitted data **Why it happens:** The field is connected to a different form than the one that submits. Usually `useForm` was called twice — once in the parent and again in a child — and the field received the child's `control` while the parent's `handleSubmit` runs. **Fix:** Call `useForm` once and pass that `control` down, or use `FormProvider`. #### `Type 'Control' is not assignable to type 'Control'` **Why it happens:** `Control` is tied to one exact form shape. A prop typed as `Control`, or as a smaller shape such as `Control<{ email: string }>`, does not accept the `control` of a larger form. **Fix:** For a component used by one form, type the prop as `Control`. For a component reused across forms, make it generic, as `TextInput` does in the example above. `name` is then checked against the form that owns `control`: ```tsx function TextInput(props: { control: Control name: FieldPath }) { // ... } ``` --- # Form Component > Use React Hook Form's Form component to validate and submit React forms to APIs or Server Actions, with built-in loading, success, and error states. Source: https://react-hook-form.com/docs/useform/form ## `Form:` [FormProps](https://react-hook-form.com/ts#FormProps) _(since v7.44.0)_ **Note**: This component is currently in **BETA** React Hook Form's `Form` component is an optional form submission component. It renders a native `
` element, runs your validation through [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit), and then sends the data to an API, a Server Action, or your callback. Loading, success, and error state end up in [`formState`](https://react-hook-form.com/docs/useform/formstate). By default, it sends a POST request with your form submission data as [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData). Set `encType` (or a `Content-Type` header via the `headers` prop) to `application/json` to send JSON instead. - Progressive enhancement for your form. - Supports both React Web and React Native. - Handles submission, including server errors. ```javascript {}} // function to be called before the request onSuccess={() => {}} // valid response onError={() => {}} // error response validateStatus={(status) => status >= 200 && status < 300} // the default /> ``` ### How it works --- When the user submits, `Form` goes through these steps: 1. **Validate.** The form is validated the same way as [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit). If validation fails, the request is not sent, and `onSubmit`, `onSuccess`, and `onError` are not called. Field errors appear in `formState.errors` as usual. 2. **`onSubmit`.** Your `onSubmit` callback is called with the validated `data` and the same values encoded as `formData` and `formDataJson`. If it returns a promise, `Form` waits for it. 3. **Send the request.** - If `action` is a URL string, `Form` calls `fetch(action, { method, headers, body })`. Then it checks the response status with `validateStatus`. It calls `onSuccess({ response })` when the status is valid, and `onError({ response })` when it is not. - If `action` is a function, `Form` calls it with the `FormData`. If the function throws, `onError({ error })` is called. - If there is no `action`, nothing is sent. Only `onSubmit` runs, so you can send the request yourself. 4. **Update form state.** `formState.isSubmitting` stays `true` until all of the above finishes. If the request fails, `formState.isSubmitSuccessful` is set to `false` and an error is set at `errors.root.server`. ### Props --- All props are optional. Any other `` attributes, such as `id`, `className`, or `aria-*`, are passed to the rendered `` element. | Name | Type | Description | Example | | ---------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | | `control` | `Control` | [`control`](https://react-hook-form.com/docs/useform/control) object provided by invoking `useForm`. Optional when using `FormProvider`. |
<Form control={control} />
| | `action` | `string \| (formData: FormData) => unknown` | URL to submit to, or _(since v7.84.0)_ a function (Server Action style) invoked with the submission's `FormData`. |
<Form action={async (formData) => { 'use server'; await save(formData) }} />
| | `method` | `"post" \| "put" \| "delete"` | HTTP method used when `action` is a URL string. `GET` is not supported since submissions are sent as a request body. Defaults to `post`. |
<Form method='post' />
| | `encType` | `"application/x-www-form-urlencoded" \| "multipart/form-data" \| "text/plain" \| "application/json"` | Sets the request's `Content-Type` and how the body is encoded. See [Request body](#requestbody). By default the submission is sent as `FormData`. |
<Form encType='application/json' />
| | `children` | `React.ReactNode` | Form contents. |
<Form>{children}</Form>
| | `render` | `({ submit }) => React.ReactNode` | Render prop for headless use, such as React Native. When `render` is set, no `` element is rendered. Call `submit()` to start the submission. |
<Form render={({ submit }) => <View/>} />
| | `onSubmit` | [`FormSubmitHandler`](https://react-hook-form.com/ts#FormSubmitHandler) | Function invoked after successful validation and before the request is sent. Receives `{ data, event, method, formData, formDataJson }`. |
<Form onSubmit={({ data }) => mutation(data)} />
| | `onSuccess` | `({ response }) => void` | Function called after a request to a URL `action` returns a status that passes `validateStatus`. |
<Form onSuccess={({ response }) => {}} />
| | `onError` | `({ response } \| { error }) => void` | Function called when the request fails. You get `{ response }` when the status fails `validateStatus`, and `{ error }` when `fetch` or a function `action` throws.

An error is also set on `formState.errors`, with `root.server` as the key. |
<Form onError={({ response }) => {}} />
| | `headers` | `Record` | Request headers object. |
<Form headers={{ accessToken:  'xxx', 'Content-Type':  'application/json'  }} />
| | `validateStatus` | `(status: number) => boolean` | Function to validate the response status code. Defaults to `status >= 200 && status < 300`. |
<Form validateStatus={status => status === 200} />
| #### onSubmit payload | Name | Type | Description | | -------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | `data` | `TTransformedValues` | The validated form values. If you use a [`resolver`](https://react-hook-form.com/docs/useform#resolver), these are the transformed values. | | `event` | `React.BaseSyntheticEvent` | The submit event. This is `undefined` when you call `submit()` from `render` without an event. | | `method` | `"post" \| "put" \| "delete"` | The `method` prop. | | `formData` | `FormData` | `data` encoded as `FormData`. This is the same body that is sent by default. | | `formDataJson` | `string` | `data` encoded with `JSON.stringify`. This is the body that is sent for JSON requests. | #### Request body The request body depends on `encType`, or on a `Content-Type` header in `headers`. The header name is matched without case sensitivity. | `encType` / `Content-Type` | Body sent | | ----------------------------------- | ----------------------------------------------------------------------------------------------- | | _(not set)_ | `FormData`. The browser sets the `multipart/form-data` header and boundary. | | `multipart/form-data` | `FormData`. `Form` does not set the `Content-Type` header, so the browser can add the boundary. | | `application/json` | `formDataJson` (the result of `JSON.stringify(data)`). | | `application/x-www-form-urlencoded` | `URLSearchParams` made from the `FormData`. Files are sent as their file name only. | | `text/plain` | One `name=value` line for each field. Files are sent as their file name only. | When values are encoded as `FormData`, nested objects and arrays use dot-notation keys, for example `user.name` and `items.0.title`. `undefined` values are skipped. Each file in a `FileList` is appended under the same key. > **Important: Rules** > > - **Data serialization:** The `` component focuses on form submission, not custom data serialization. Type-specific transformations (e.g. `Date`, `Dayjs`, or custom objects) should be handled at the application level before submission. We aim to keep the component lightweight and avoid introducing additional serialization rules. > > - If you want to prepare or omit submission data, please use [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit) or `onSubmit`. > ```javascript > const { handleSubmit, control } = useForm(); > const onSubmit =(data) => callback(prepareData(data)) > > // or > onSubmit={({ data }) => { > console.log(data) > }} > /> > ``` > - Progressive enhancement is only applicable to SSR frameworks. > > ```javascript > const { handleSubmit, control } = useForm({ > progressive: true > }); > > > > > > // Renders > >
> >
> ``` > > - `Form` needs a `control`. Pass it as a prop, or render `Form` inside a [`FormProvider`](https://react-hook-form.com/docs/formprovider). > - `onSuccess` is only called for a URL string `action`. When `action` is a function, there is no response to check, so treat the end of the submission as success, for example with `formState.isSubmitSuccessful`. > - `onError` is only for request errors. Validation errors do not call `onError`; read them from `formState.errors`. > - The `
` element gets `noValidate` only after it mounts. Before hydration, the browser's native validation (from `progressive: true`) protects the form. After hydration, React Hook Form validates it. > ### Form component vs handleSubmit --- Both APIs validate with the rules configured in `useForm`. Choose based on who should own the request: | Use | Best when | | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`Form`](https://react-hook-form.com/docs/useform/form) | You want React Hook Form to encode the data, send the request, and expose request success or failure through `formState`. It also supports progressive enhancement and function actions. | | [`handleSubmit`](https://react-hook-form.com/docs/useform/handlesubmit) | You need complete control over the submission, such as retries, cancellation, multiple requests, custom serialization, or integration with a data-fetching library. | Use `Form` with a URL `action` for a conventional API endpoint, a function `action` for a Server Action-style workflow, or no `action` when your `onSubmit` callback sends the request itself. ### Examples --- **React Web** ```javascript import { useForm, Form } from "react-hook-form" function App() { const { control, register, formState: { isSubmitSuccessful, errors }, } = useForm({ // progressive: true, optional prop for progressive enhancement }) return (
{/* Use action prop to make post submission with formData */} { alert("Success") }} onError={() => { alert("error") }} > {isSubmitSuccessful &&

Form submit successful.

} {errors?.root?.server &&

Form submit failed.

} {/* Manual form submission */}
{ await fetch("api", { method: "post", body: formData, }) }} >
) } ``` **Send JSON and show the submission state** ```tsx import { useForm, Form } from "react-hook-form" type FormValues = { email: string } function App() { const { control, register, formState: { isSubmitting, isSubmitSuccessful, errors }, } = useForm() return (
{ // response is undefined when the network request itself failed if (response) console.error(await response.text()) }} > {errors.email &&

{errors.email.message}

} {errors.root?.server && (

Something went wrong ({errors.root.server.type || "network error"}).

)} {isSubmitSuccessful &&

Thanks for subscribing!

}
) } ``` `errors.root.server.type` holds the response status as a string, such as `"500"`. It is an empty string when `fetch` or a function `action` throws. **Server Action** ```tsx // actions.ts "use server" export async function createPost(formData: FormData) { await db.post.create({ data: { title: String(formData.get("title")) } }) } ``` ```tsx "use client" import { useForm, Form } from "react-hook-form" import { createPost } from "./actions" export function PostForm() { const { control, register, formState: { isSubmitSuccessful, errors }, } = useForm({ progressive: true }) return (
{errors.root?.server &&

Could not save the post.

} {isSubmitSuccessful &&

Post created.

}
) } ``` When `action` is a function, `Form` does not render `method` or `encType` on the `
` element, because React manages those for Server Actions. **With FormProvider** ```javascript import { useForm, FormProvider, Form, useFormContext } from "react-hook-form" function NameInput() { const { register } = useFormContext() return } function App() { const methods = useForm() return ( {/* No control prop: Form reads it from FormProvider */}
) } ``` **File upload** ```javascript import { useForm, Form } from "react-hook-form" function App() { const { control, register } = useForm() return (
{/* each selected file is appended under "attachments" */}
) } ``` **React Native** ```javascript import { useForm, Form } from "react-hook-form" function App() { const { control, register, formState: { isSubmitSuccessful, errors }, } = useForm() return (
( {isSubmitSuccessful && Form submit successful.} {errors?.root?.server && Form submit failed.} ) } ``` ### Tips --- - Use `getErrors` in event handlers and effects where you need the current errors but do not want a re-render. For example, in a multi-step form, find which steps have errors after validation: ```javascript const onNext = async () => { await trigger() const [account, address] = getErrors(["account", "address"]) setStepsWithErrors({ account: !!account, address: !!address }) } ``` - Do not render from `getErrors`. The value is not reactive, so the UI does not update when errors change. Use [`formState.errors`](https://react-hook-form.com/docs/useform/formstate) or [`ErrorMessage`](https://react-hook-form.com/docs/useformstate/errormessage) for UI. ### Troubleshooting --- #### `getErrors()` is empty even though a field value is invalid **Why it happens:** `getErrors` reads errors that are already stored; it does not run validation. If the current validation mode has not checked the field yet, there is no error to return. **Fix:** Validate first, then read the result: ```javascript await trigger("email") const emailError = getErrors("email") ``` #### An error rendered with `getErrors` does not update **Why it happens:** `getErrors` intentionally does not subscribe or cause a re-render. It is a snapshot API for handlers and effects. **Fix:** Render errors with [`ErrorMessage`](https://react-hook-form.com/docs/useformstate/errormessage), `formState.errors`, or `useFormState({ name })`. Keep `getErrors` for imperative reads. --- # getFieldState > Get the current validation and interaction state of a specific field — invalid, isDirty, isTouched, and error — from React Hook Form. Source: https://react-hook-form.com/docs/useform/getfieldstate ## `getFieldState:` [UseFormGetFieldState](https://react-hook-form.com/ts#UseFormGetFieldState) _(since v7.25.0)_ This method returns individual field state. It is useful for retrieving nested field state in a type-safe way. ### Props --- | Name | Type | Description | | --------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | registered field name. | | formState | `object` | This is an optional prop, which is only required if `formState` has not been read from or subscribed to via `useForm`, `useFormContext` or `useFormState`. See the rules below for more information. | ### Return --- | Name | Type | Description | | ------------ | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `isDirty` | `boolean` | field is modified.
**Condition:** subscribe to `dirtyFields`. | | isTouched | `boolean` | field has received a focus and blur event.
**Condition:** subscribe to `touchedFields`. | | invalid | `boolean` | field is not valid.
**Condition:** subscribe to `errors`. | | isValidating | `boolean` | _(since v7.51.0)_ field is currently being validated.
**Condition:** subscribe to `isValidating`. | | error | `undefined \| FieldError` | field error object.
**Condition:** subscribe to `errors`. | > **Important: Rules** > > - The prop must match a registered field name. > ```javascript > register("test") // registers the input > getFieldState("test") // ✅ returns state for the registered field > getFieldState("non-existent-name") // ❌ returns default/false state since this name was never registered > ``` > - `getFieldState` works by subscribing to form state updates, and you can subscribe to the formState in the following ways: > - You can subscribe at the `useForm`, `useFormContext` or `useFormState`. This is will establish the form state subscription and `getFieldState` second argument will no longer be required. > > ```javascript > const { > register, > formState: { isDirty }, > } = useForm() > register("test") > getFieldState("test") // ✅ > ``` > > ```javascript > const { isDirty } = useFormState() > register("test") > getFieldState("test") // ✅ > ``` > > ```javascript > const { > register, > formState: { isDirty }, > } = useFormContext() > register("test") > getFieldState("test") // ✅ > ``` > > - When form state subscription is not set up, you can pass the entire `formState` as the second optional argument by following the example below: > ```javascript > const { register } = useForm() > register("test") > const { isDirty } = getFieldState("test") // ❌ formState isDirty is not subscribed at useForm > const { register, formState } = useForm() > const { isDirty } = getFieldState("test", formState) // ✅ formState.isDirty subscribed > const { formState } = useFormContext() > const { isTouched } = getFieldState("test", formState) // ✅ formState.touchedFields subscribed > ``` > ### Examples --- [Open in CodeSandbox](https://codesandbox.io/s/getfieldstate-jvekk) ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, getFieldState, formState: { isDirty, isValid }, } = useForm({ mode: "onChange", defaultValues: { firstName: "", }, }) // you can invoke before render or within the render function const fieldState = getFieldState("firstName") return (
{" "}

{getFieldState("firstName").isDirty && "dirty"}

{" "}

{getFieldState("firstName").isTouched && "touched"}

) } ``` ### Tips --- - In a reusable field component, subscribe to only that field with `useFormState({ name })`, and pass the result to `getFieldState`. The component then re-renders only when that field's state changes: ```javascript function FieldError({ name }) { const { getFieldState } = useFormContext() const formState = useFormState({ name }) const { error, isTouched } = getFieldState(name, formState) return isTouched && error ?

{error.message}

: null } ``` - `getFieldState` is typed against your form values, so a misspelled nested path is a type error. Reading `errors.some.deep.path` by hand is not checked in the same way. ### Troubleshooting --- #### `isDirty`, `isTouched`, and `invalid` are always `false` **Why it happens:** The field name may not be registered, or the component has not subscribed to the matching form-state properties. `getFieldState` reads state; it does not create every subscription by itself. **Fix:** Check that the name exactly matches a registered field. Then read the required state from `formState`, or pass a scoped `useFormState` result: ```javascript const formState = useFormState({ control, name: "email" }) const emailState = getFieldState("email", formState) ``` #### A field state is stale inside an event handler **Why it happens:** The component never subscribed to the state being read. Reading `getFieldState` only inside a click handler does not cause the component to re-render when that state changes. **Fix:** For reactive UI, call `useFormState({ name })` during render and pass its result to `getFieldState`. For a one-time read, call `getFieldState` in the handler after the operation that updates the field. --- # getValues > Read current form values without subscribing to re-renders. Retrieve a single field, multiple fields, or the entire form data object. Source: https://react-hook-form.com/docs/useform/getvalues ## `getValues:` [UseFormGetValues](https://react-hook-form.com/ts#UseFormGetValues) An optimized helper for reading form values. The difference between `watch` and `getValues` is that `getValues` **will not** trigger re-renders or subscribe to input changes. ### Props --- | Name | | Type | Description | | ------------ | --------------- | ------------------------------ | --------------------------------------------------------- | | `fieldNames` | | `undefined` | Returns the entire form values. | | | | `string` | Gets the value at path of the form values. | | | | `string[]` | Returns an array of the value at path of the form values. | | `config` | `dirtyFields` | `boolean` | _(since v7.63.0)_ Returns only dirty fields. | | | `touchedFields` | `boolean` | _(since v7.63.0)_ Returns only touched fields. | ##### Examples --- The example below shows what to expect when you invoke `getValues` method. ```jsx ``` | Name | Output | | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `getValues()` | `{ root: { test1: '', test2: ''} }` | | `getValues("root")` | `{ test1: '', test2: ''}` | | `getValues("root.test1")` | `''` | | `getValues(["root.test1", "root.test2"])` | `['', '']` | | `getValues(undefined, { dirtyFields: true })` | `{ root: { test1: '' } }` — only fields present in `formState.dirtyFields` (e.g. after editing `test1`) are included | | `getValues(undefined, { touchedFields: true })` | `{ root: { test1: '' } }` — only fields present in `formState.touchedFields` (e.g. after blurring `test1`) are included | > **Important: Rules** > > - It will return `defaultValues` from `useForm` before the **initial** render. > - `getValues` returns the raw field values. The data passed to your `handleSubmit` callback can differ: with a [resolver](https://react-hook-form.com/docs/useform#resolver) it's the resolver's output (with any transforms or coercion applied), and disabled fields are left out. > - `getValues` doesn't subscribe to changes, so it won't re-render your component. To render a value, use [`useWatch`](https://react-hook-form.com/docs/usewatch) or [`watch`](https://react-hook-form.com/docs/useform/watch). > ### Examples --- **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-ts-getvalues-txsfg) ```tsx import { useForm } from "react-hook-form" type FormInputs = { test: string test1: string } export default function App() { const { register, getValues } = useForm() return (
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-getvalues-2eioh) ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, getValues } = useForm() return (
) } ``` **Types** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-ts-getvalues-txsfg) ```tsx import { useForm } from "react-hook-form" // Flat input values type Inputs = { key1: string key2: number key3: boolean key4: Date } function FlatForm() { const { register, getValues } = useForm() getValues() return
} // Nested input values type Inputs1 = { key1: string key2: number key3: { key1: number key2: boolean } key4: string[] } function NestedForm() { const { register, getValues } = useForm() getValues() // function getValues(): Inputs1 getValues("key1") // function getValues<"key1">(name: "key1"): string getValues("key2") // function getValues<"key2">(name: "key2"): number getValues("key3.key1") // function getValues<"key3.key1">(name: "key3.key1"): number getValues("key3.key2") // function getValues<"key3.key2">(name: "key3.key2"): boolean getValues("key4") // function getValues<"key4">(name: "key4"): string[] getValues(["key1", "key3.key2"]) // function getValues<["key1", "key3.key2"]>(names: readonly ["key1", "key3.key2"]): [string, boolean] return } ``` ### Tips --- - To compare fields inside a validation rule, use the second argument of `validate` instead of `getValues`. It gets the current form values: ```javascript register("confirmPassword", { validate: (value, formValues) => value === formValues.password || "Passwords do not match", }) ``` - Do not mutate the object that `getValues` returns. Nested objects are shared with the form's internal state, so changing them can change form values without updating the form state. Copy the value first, or use [`setValue`](https://react-hook-form.com/docs/useform/setvalue). - Use `getValues` in event handlers, for example to build a preview or to save a draft on click. In those places you need the latest values once, not a subscription. ### Troubleshooting --- #### A value shown with `getValues` doesn't update as the user types **Why it happens:** `getValues` reads the current values once and does not subscribe to changes, so the component does not re-render when the input changes. **Fix:** To render a value, use [`useWatch`](https://react-hook-form.com/docs/usewatch) (or [`watch`](https://react-hook-form.com/docs/useform/watch)), which re-renders when the value changes. Keep `getValues` for event handlers. --- # handleSubmit > Validate form inputs and invoke your submit callback with typed form data, or pass errors to an error handler on validation failure. Source: https://react-hook-form.com/docs/useform/handlesubmit ## `handleSubmit:` [UseFormHandleSubmit](https://react-hook-form.com/ts#UseFormHandleSubmit) This function will receive the form data if form validation is successful. ### Props --- | Name | Type | Description | | ------------------ | --------------------------------------------------------------------------------------------------- | ---------------------- | | SubmitHandler | `(data: TFieldValues, e?: BaseSyntheticEvent) => TResult \| Promise` | A successful callback. | | SubmitErrorHandler | `(errors: FieldErrors, e?: BaseSyntheticEvent) => unknown \| Promise` | An error callback. | > **Important: Rules** > > - _(since v7.84.0)_ The promise returned by calling > `handleSubmit(onValid)(event)` resolves with whatever `onValid` returns, > instead of discarding it. > > ```javascript > const onValid = (data) => ({ id: data.id }) > const result = await handleSubmit(onValid)() // result: { id: string } | undefined > ``` > > - `formState.isSubmitting` stays `true` until the promise returned by `onSubmit` settles, so `await` (or return) your async work: > > ```javascript > const onSubmit = async (data) => { > await fetch("/api", { method: "POST", body: JSON.stringify(data) }) // ✅ isSubmitting stays true until this resolves > } > ``` > > - `disabled` inputs will appear as `undefined` values in form values. If you want to prevent users from updating an input and wish to retain the form value, you can use `readOnly` or disable the entire <fieldset />. Here is an [example](https://codesandbox.io/s/react-hook-form-disabled-inputs-oihxx). > - `handleSubmit` function will not swallow errors that occurred inside your onSubmit callback, so we recommend that you use try/catch blocks inside your async requests and handle those errors gracefully for your customers. Use `setError` inside the catch block to register a server-side error — this also ensures `formState.isSubmitSuccessful` is set to `false`. > > ```javascript > const onSubmit = async (data) => { > // async request which may result error > try { > // await fetch() > } catch (e) { > setError("root.serverError", { > type: e.status, > message: e.message, > }) > } > } > > return > ``` > > - To submit from a button outside the ``, either link the button to the form with the native `form` attribute, or call the returned function directly: > > ```javascript > ... > > // ✅ native form attribute > // ✅ call handleSubmit directly > ``` > > - React's `submit` event bubbles through the component tree, including portals. If a form is rendered inside another form (for example in a modal), stop propagation so the outer form doesn't submit too: > > ```javascript >
onSubmit={(event) => { > event.stopPropagation() > handleSubmit(onInnerSubmit)(event) > }} > /> > ``` > > - For submitting with React Server Actions or `useActionState`, see [Server Actions](https://react-hook-form.com/advanced-usage/server-actions). To test your submit flow, see [Testing Form](https://react-hook-form.com/advanced-usage/testing). > ### Examples --- **Sync** **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-handlesubmit-ts-v7-lcrtu) ```tsx import { useForm, SubmitHandler, SubmitErrorHandler } from "react-hook-form" type FormValues = { firstName: string lastName: string email: string } export default function App() { const { register, handleSubmit } = useForm() const onSubmit: SubmitHandler = (data) => console.log(data) const onError: SubmitErrorHandler = (errors) => console.log(errors) return ( ) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-handlesubmit-v7-uqmiy) ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit } = useForm() const onSubmit = (data, e) => console.log(data, e) const onError = (errors, e) => console.log(errors, e) return (
) } ``` **Async** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-async-submit-validation-kpx0o) ```javascript import { useForm } from "react-hook-form" const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) function App() { const { register, handleSubmit, formState: { errors }, } = useForm() const onSubmit = async (data) => { await sleep(2000) if (data.username === "bill") { alert(JSON.stringify(data)) } else { alert("There is an error") } } return (
) } ``` **Resolver with transformed values** When a resolver (Zod, Yup, Joi, or custom) transforms the submitted data — so the output type differs from the field input type — use `useForm`'s third generic, `TTransformedValues`, to tell TypeScript what `handleSubmit` will receive. Without it, the callback is typed as the input (field) type and you'll get errors accessing transformed properties. ```tsx import { useForm, SubmitHandler } from "react-hook-form" import { zodResolver } from "@hookform/resolvers/zod" import * as z from "zod" // Example using Zod — the same pattern applies to any resolver whose // output type differs from its input type (Yup, Joi, custom, etc.) const schema = z .object({ emailOrPhone: z.string().trim(), }) .transform(({ emailOrPhone }) => ({ isEmail: emailOrPhone.includes("@"), isPhone: /^\d+$/.test(emailOrPhone), value: emailOrPhone, })) type FormInput = z.input // { emailOrPhone: string } type FormOutput = z.output // { isEmail: boolean; isPhone: boolean; value: string } export default function App() { // 1st generic = field/input type (drives register, watch, etc.) // 3rd generic = transformed output type (drives handleSubmit callback) const { register, handleSubmit } = useForm({ resolver: zodResolver(schema), }) const onSubmit: SubmitHandler = (data) => { console.log(data.isEmail, data.isPhone, data.value) } return (
) } ``` --- ### Video --- The following video tutorial explains the `handleSubmit` API in detail. [Watch on YouTube](https://www.youtube.com/watch?v=KzcPKB9SOEk) ### Tips --- - `handleSubmit` does not block a second submission while the first one is still pending. Disable the submit button with `formState.isSubmitting`, or check it at the start of your handler. - Use the second argument, `onInvalid`, to react to failed validation, for example to log analytics or open the section that contains the first error: ```javascript handleSubmit(onValid, (errors) => { analytics.track("form_invalid", { fields: Object.keys(errors) }) }) ``` - Transform the data inside `onValid` (or in your resolver) and not in the inputs. Inputs keep their raw values, and you send the shape your API needs. - When you call `handleSubmit(onValid)()` without an event, nothing calls `preventDefault`. Use this to submit from a keyboard shortcut or a timer. ### Troubleshooting --- #### `onSubmit` is never called and nothing happens **Why it happens:** Validation failed. `handleSubmit` only calls your handler when every field is valid. If you do not render `errors`, the form looks like it ignores the click. **Fix:** Render `formState.errors`, or pass a second callback to see what failed: ```javascript
console.log(errors))}> ``` #### The page reloads and `onSubmit` never runs **Why it happens:** `handleSubmit(onSubmit)` returns the submit handler. Wrapping it in an arrow function, as in `onSubmit={() => handleSubmit(onSubmit)}`, creates that handler but never calls it, so the browser submits the form natively and reloads the page. **Fix:** Pass the result directly: ```javascript ``` #### An error thrown in `onSubmit` is not shown to the user **Why it happens:** If `onSubmit` throws (or its promise rejects), `handleSubmit` rethrows the error and sets `isSubmitSuccessful` to `false`. Nothing is added to `formState.errors`. **Fix:** Catch the error and store it with [`setError`](https://react-hook-form.com/docs/useform/seterror) under a `root` key: ```javascript const onSubmit = async (data) => { try { await save(data) } catch { setError("root.server", { message: "Could not save. Try again." }) } } { errors.root?.server &&

{errors.root.server.message}

} ``` --- # register > Register an input with React Hook Form to enable validation, value tracking, and form submission. Supports text, checkbox, select, and more. Source: https://react-hook-form.com/docs/useform/register ## `register:` [UseFormRegister](https://react-hook-form.com/ts#UseFormRegister) This method allows you to register an input or select element and apply validation rules in React Hook Form. Validation rules are all based on the HTML standard and also allow for custom validation methods. ### Props --- | Name | Type | Description | | --------- | ------------------------------------ | ----------------- | | `name` | `string` | Input's name. | | `options` | `RegisterOptions` | Input's behavior. | ### Return --- | Name | Type | Description | | ----------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `ref` | `React.Ref` | React element ref used to connect hook form to the input. | | `name` | `string` | Input's name being registered. | | `onChange` | `ChangeHandler` | `onChange` prop to subscribe to the input change event. | | `onBlur` | `ChangeHandler` | `onBlur` prop to subscribe to the input blur event. | | `min` | `string \| number` | _(since v7.21.0)_ Present only when [`progressive`](https://react-hook-form.com/docs/useform#progressive) is `true`; reflects the `min` rule if one was set (otherwise `undefined`). | | `max` | `string \| number` | _(since v7.21.0)_ Present only when `progressive` is `true`; reflects the `max` rule if one was set (otherwise `undefined`). | | `maxLength` | `number` | _(since v7.21.0)_ Present only when `progressive` is `true`; reflects the `maxLength` rule if one was set (otherwise `undefined`). | | `minLength` | `number` | _(since v7.21.0)_ Present only when `progressive` is `true`; reflects the `minLength` rule if one was set (otherwise `undefined`). | | `pattern` | `string` | _(since v7.21.0)_ Present only when `progressive` is `true`; reflects the `pattern` rule if one was set (otherwise `undefined`). | | `required` | `boolean` | _(since v7.21.0)_ Present only when `progressive` is `true`; reflects the `required` rule if one was set (otherwise `false`). | | `disabled` | `boolean` | _(since v7.21.0)_ _optional_. Present when the `disabled` option is set. | > **note** > > This is how submitted values will look like: > > | Input Name | Submit Result | > | ------------------------------------------------- | --------------------------------------------------------- | > | `register("firstName")` | `{ firstName: value }` | > | `register("name.firstName")` | `{ name: { firstName: value } }` | > | `register("name.firstName.0")` | `{ name: { firstName: [ value ] } }` | > ### Options --- By selecting the register option, the API table below will get updated. > **note** > > These are validation rules, not native HTML attributes. They run based on the form's [`mode`](https://react-hook-form.com/docs/useform#mode) and don't block typing. To also forward `required`, `min`, `max`, `minLength`, `maxLength`, and `pattern` as native attributes on the input, set [`progressive`](https://react-hook-form.com/docs/useform#progressive) to `true` on `useForm`. >
| Name | Description | | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `required` `boolean` | Indicates that the input must have a value before the form can be submitted.

**Note:** This config aligns with web constrained API for required input validation, for object or array input types, use the validate function instead. | | `maxLength` `number` | The maximum length of the value to accept for this input. | | `minLength` `number` | The minimum length of the value to accept for this input. | | `max` `number` | The maximum value to accept for this input. | | `min` `number` | The minimum value to accept for this input. | | `pattern` `RegExp` | The regex pattern for the input.

**Note:** `RegExp` with the `/g` flag keeps track of the last index where a match occurred. | | `validate` Function \|
`Record` | Validate function will be executed on its own without depending on other validation rules included in the required attribute. The function receives the field value (and, _(since v7.42.0)_ optionally the full form values as a second argument) and must return one of:
  • `true` or `undefined` — field is valid (both are treated identically; explicit `return true` is conventional but not required)
  • A `string` — field is invalid; the string is used as the error message
  • `false` — field is invalid with no custom message (a generic error is used)
Pass an object of named functions to run multiple independent validations, each with its own error message.

**Note:** for object or array input data, it's recommended to use the validate function for validation as the other rules mostly apply to strings, arrays of strings, numbers, and booleans. | | `valueAsNumber` `boolean` | Returns `Number` normally. If something goes wrong `NaN` will be returned.
  • `valueAs` process is happening **before** validation.
  • Only applies to number input, but without any data manipulation.
  • Does not transform `defaultValue` or `defaultValues`.
| | `valueAsDate` `boolean` | Returns `Date` normally. If something goes wrong `Invalid Date` will be returned.
  • `valueAs` process is happening **before** validation.
  • Only applies to input.
  • Does not transform `defaultValue` or `defaultValues`.
| | `setValueAs` \(value: any) => T | Return input value by running through the function.
  • `valueAs` process is happening **before** validation. Also, `setValueAs` is ignored if either `valueAsNumber` or `valueAsDate` are true.
  • Only applies to text input.
  • Does not transform `defaultValue` or `defaultValues`.
| | `disabled` `boolean = false` | _(since v7.13.0)_ Set `disabled` to `true` will lead input value to be `undefined` and input control to be disabled.
  • `disabled` prop will also omit built-in validation rules.
  • For schema validation, you can leverage the `undefined` value returned from input or context object.
| | `onChange` `(e: SyntheticEvent) => void` | _(since v7.16.0)_ `onChange` function event to be invoked in the change event. | | `onBlur` `(e: SyntheticEvent) => void` | _(since v7.16.0)_ `onBlur` function event to be invoked in the blur event. | | `value` `unknown` | _(since v7.8.0)_ Set up `value` for the registered input. This prop should be utilised inside `useEffect` or invoked once, each re-run will update or overwrite the input value which you have supplied. | | `shouldUnregister` `boolean` | Input will be unregistered after unmount and `defaultValues` will be removed as well.

**Note:** this prop should be avoided when using with `useFieldArray` as unregister function gets called after input unmount/remount and reorder. | | `deps` `string \| string[]` | _(since v7.14.0)_ When this field's own validation runs (e.g. via its registered `onChange`/`onBlur`), the fields listed in `deps` will also be re-validated. Calling `trigger()` manually does not honor `deps`. |
| Name | Description | | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `required` string \|
{ value: boolean, message: string } | Indicates that the input must have a value before the form can be submitted.

**Note:** This config aligns with web constrained API for required input validation, for object or array input types, use the validate function instead. | | `maxLength` `{ value: number, message: string }` | The maximum length of the value to accept for this input. | | `minLength` `{ value: number, message: string }` | The minimum length of the value to accept for this input. | | `max` `{ value: number, message: string }` | The maximum value to accept for this input. | | `min` `{ value: number, message: string }` | The minimum value to accept for this input. | | `pattern` `{ value: RegExp, message: string }` | The regex pattern for the input.

**Note:** `RegExp` with the `/g` flag keeps track of the last index where a match occurred. | | `validate` Function \|
`Record` | Validate function will be executed on its own without depending on other validation rules included in the required attribute. The function receives the field value (and, _(since v7.42.0)_ optionally the full form values as a second argument) and must return one of:
  • `true` or `undefined` — field is valid (both are treated identically; explicit `return true` is conventional but not required)
  • A `string` — field is invalid; the string is used as the error message
  • `false` — field is invalid with no custom message (a generic error is used)
Pass an object of named functions to run multiple independent validations, each with its own error message.

**Note:** for object or array input data, it's recommended to use the validate function for validation as the other rules mostly apply to strings, arrays of strings, numbers, and booleans. | | `valueAsNumber` `boolean` | Returns `Number` normally. If something goes wrong `NaN` will be returned.
  • `valueAs` process is happening **before** validation.
  • Only applies to number input, but without any data manipulation.
  • Does not transform `defaultValue` or `defaultValues`.
| | `valueAsDate` `boolean` | Returns `Date` normally. If something goes wrong `Invalid Date` will be returned.
  • `valueAs` process is happening **before** validation.
  • Only applies to input.
  • Does not transform `defaultValue` or `defaultValues`.
| | `setValueAs` \(value: any) => T | Return input value by running through the function.
  • `valueAs` process is happening **before** validation. Also, `setValueAs` is ignored if either `valueAsNumber` or `valueAsDate` are true.
  • Only applies to text input.
  • Does not transform `defaultValue` or `defaultValues`.
| | `disabled` `boolean = false` | _(since v7.13.0)_ Set `disabled` to `true` will lead input value to be `undefined` and input control to be disabled.
  • `disabled` prop will also omit built-in validation rules.
  • For schema validation, you can leverage the `undefined` value returned from input or context object.
| | `onChange` `(e: SyntheticEvent) => void` | _(since v7.16.0)_ `onChange` function event to be invoked in the change event. | | `onBlur` `(e: SyntheticEvent) => void` | _(since v7.16.0)_ `onBlur` function event to be invoked in the blur event. | | `value` `unknown` | _(since v7.8.0)_ Set up `value` for the registered input. This prop should be utilised inside `useEffect` or invoked once, each re-run will update or overwrite the input value which you have supplied. | | `shouldUnregister` `boolean` | Input will be unregistered after unmount and `defaultValues` will be removed as well.

**Note:** this prop should be avoided when using with `useFieldArray` as unregister function gets called after input unmount/remount and reorder. | | `deps` `string \| string[]` | _(since v7.14.0)_ When this field's own validation runs (e.g. via its registered `onChange`/`onBlur`), the fields listed in `deps` will also be re-validated. Calling `trigger()` manually does not honor `deps`. |
> **Important: Rules** > >
    >
  • > Name is required and must be unique > (except for native radio and checkbox inputs). >
  • >
  • > Names must not start with a number or use numbers as standalone keys, and should avoid special characters. > For TypeScript consistency, only dot syntax is supported—bracket syntax ([]) will not work for array form values. > > ```javascript > register("test.0.firstName") // ✅ > register("test[0].firstName") // ❌ > ``` > >
  • > >
  • Disabled inputs return undefined as their form value. > If you need to prevent user edits while preserving the value, use > readOnly or disable the entire fieldset. Here is an [example](https://codesandbox.io/s/react-hook-form-disabled-inputs-oihxx).
  • > >
  • Changing an input’s name on each render causes it to be re-registered as a new field. > To ensure consistent behavior, keep input names stable across renders.
  • > >
  • Input values and references are not automatically removed on unmount. > Use unregister to explicitly remove them when needed.
  • > >
  • > Calling register again on the same name merges the new options into the existing ones — it does not replace them — so individual register options cannot be removed using `undefined` or `{}`. You can update individual attributes instead. > > ```javascript > register('test', { required: true }); > register('test', {}); // ❌ > register('test', undefined); // ❌ > register('test', { required: false }); // ✅ > ``` > >
  • > >
  • There are certain keywords that should be avoided to prevent conflicts with type checks. They are `ref` and `_f`.
  • > >
> ### Examples --- **Register input or select** [Open in CodeSandbox](https://codesandbox.io/s/register-is0sfo) ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit } = useForm({ defaultValues: { firstName: "", lastName: "", category: "", checkbox: [], radio: "", }, }) return (
) } ``` **Custom async validation** ```javascript import { useForm } from "react-hook-form" import { checkProduct } from "./service" export default function App() { const { register, handleSubmit } = useForm() return (
{ if (!category) return "Choose a category" if (!product) return "Specify your product" const isInStock = await checkProduct(category, product) return isInStock || "There is no such product" }, }, })} />
) } ``` **File input** A file input's value is a `FileList`, not a string. `required` works as usual, use `validate` to check things like file size, and build a `FormData` from the files when you submit. ```tsx import { useForm } from "react-hook-form" type FormValues = { avatar: FileList } export default function App() { const { register, handleSubmit, formState: { errors }, } = useForm() const onSubmit = async ({ avatar }: FormValues) => { const body = new FormData() body.append("avatar", avatar[0]) await fetch("/api/avatar", { method: "POST", body }) } return (
!files?.[0] || files[0].size < 2_000_000 || "Max size is 2 MB", })} /> {errors.avatar &&

{errors.avatar.message}

}
) } ``` ### Video --- [Watch on YouTube](https://www.youtube.com/watch?v=JFIpCoajYkA) ### Tips --- #### Destructuring assignment ```javascript const { onChange, onBlur, name, ref } = register('firstName'); // Include a type check against the field path with the name you have supplied. // same as above ``` #### Custom Register You can also register inputs with `useEffect` and treat them as virtual inputs. For controlled components, we provide a custom hook [useController](https://react-hook-form.com/docs/usecontroller) and [Controller](https://react-hook-form.com/docs/usecontroller/controller) component to take care of this process for you. If you choose to manually register fields, you will need to update the input value with [setValue](https://react-hook-form.com/docs/useform/setvalue). ```javascript register("firstName", { required: true, minLength: 8 }) ; setValue("firstName", value)} /> ``` #### How to work with `innerRef`, `inputRef`? When the custom input component doesn't expose the ref correctly, you can get it working via the following method. ```javascript // not working, because ref is not assigned const firstName = register('firstName', { required: true }) ``` If you also need the input's ref yourself, see [How to share ref usage](https://react-hook-form.com/faqs#Howtosharerefusage). ### Troubleshooting --- #### A number input is submitted as a string **Why it happens:** Input values in the DOM are always strings, so `` gives you `"5"`, not `5`. **Fix:** Add `valueAsNumber`, or `setValueAs` for your own conversion: ```javascript ``` #### A field in a custom input component is missing from the submitted data **Why it happens:** `register` reads the value through the `ref` of the actual ``. If your component takes the props but does not pass `ref` on to the ``, the field has no value and cannot be focused on errors. **Fix:** Pass all props, including `ref`, to the ``. If the component uses a different prop name such as `inputRef`, see [How to work with `innerRef`, `inputRef`](#HowtoworkwithinnerRefinputRef). #### A field registered with `disabled: true` is missing from the submitted data **Why it happens:** Disabling a field through `register` excludes its value from the data passed to `handleSubmit`. **Fix:** If the user should see the value but not change it, and you still need it in the submitted data, use `readOnly` instead: ``. --- # reset > Reset the entire form to default values, clearing all errors, dirty fields, and touched state in React Hook Form. Source: https://react-hook-form.com/docs/useform/reset ## `reset:` [UseFormReset](https://react-hook-form.com/ts#UseFormReset) Reset the entire form state, fields reference, and subscriptions. There are optional arguments that allow partial form state reset. ### Props --- `Reset` has the ability to retain formState. Here are the options you may use: | Name | | Type | Description | | --------- | ------------------------ | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `values` | | `object \| (values: Object) => Object` | An optional object to reset form values, and it's recommended to provide the **entire** defaultValues when supplied. _(since v7.36.0)_ Also accepts a callback that receives the current form values and returns the next values. | | `options` | `keepErrors` | `boolean` | All errors will remain. This behavior is not guaranteed after further user actions. | | | `keepDirty` | `boolean` | `DirtyFields` form state will remain, and `isDirty` will temporarily remain as the current state until further user's action.

**Important:** this keep option doesn't reflect form input values but only dirty fields form state. | | | `keepDirtyValues` | `boolean` | _(since v7.31.0)_ `DirtyFields` and `isDirty` will remain, and only non-dirty fields will be updated to the newly provided values. [Check out the example.](https://codesandbox.io/s/react-keepdirtyvalues-o8to91)

**Important:** formState `dirtyFields` will need to be subscribed. | | | `keepValues` | `boolean` | Form input values will be unchanged. | | | `keepDefaultValues` | `boolean` | Keep the same defaultValues which are initialised via `useForm`.
  • `isDirty` will be checked again: it is set to the result of the comparison of any new values provided against the original `defaultValues`.
  • `dirtyFields` will be updated again if values are provided: it is set to the result of the comparison between the new values provided against the original `defaultValues`.
| | | `keepIsSubmitted` | `boolean` | `isSubmitted` state will be unchanged. | | | `keepIsSubmitSuccessful` | `boolean` | _(since v7.47.0)_ `isSubmitSuccessful` state will be unchanged. | | | `keepTouched` | `boolean` | `isTouched` state will be unchanged. | | | `keepIsValidating` | `boolean` | _(since v7.51.0)_ `isValidating`/`validatingFields` state will be unchanged, rather than cleared by the reset. | | | `keepIsValid` | `boolean` | `isValid` will temporarily persist as the current state until additional user actions. | | | `keepSubmitCount` | `boolean` | `submitCount` state will be unchanged. | | | `keepFieldsRef` | `boolean` | _(since v7.60.0)_ Preserve the internal field references (registered inputs). Useful when you want to reset form values without causing inputs to unmount and remount. | > **Important: Rules** > > - It is recommended to always provide defaultValues when resetting a form > to ensure all inputs, especially controlled components, are restored correctly. > - Avoid calling `reset` inside `onSubmit`. `handleSubmit` updates `isSubmitted`, `isSubmitSuccessful` and `submitCount` after your handler finishes, so a `reset` there clears the values but not the submission state. Reset in a `useEffect` when `formState.isSubmitSuccessful` becomes `true` instead (see the **Submit with Reset** example below). > - Calling `reset` with `values` updates the form's `defaultValues` unless `options.keepDefaultValues` is set. If `reset` is later called without `values` or with `{}`, the form resets to the last `values` provided instead of the initial `defaultValues`. > ### Examples --- **Uncontrolled** **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-reset-v7-ts-pu901) ```tsx import { useForm } from "react-hook-form" interface UseFormInputs { firstName: string lastName: string } export default function Form() { const { register, handleSubmit, reset, formState: { errors }, } = useForm() const onSubmit = (data: UseFormInputs) => { console.log(data) } return (
reset()} value="Custom Reset Field Values & Errors" />
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-reset-v7-r7m5s) ```javascript import { useCallback, useEffect } from "react" import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit, reset } = useForm() const resetAsyncForm = useCallback(async () => { const response = await fetch("./api/formValues.json") const result = await response.json() // result: { firstName: 'test', lastName: 'test2' } reset(result) // asynchronously reset your form values }, [reset]) useEffect(() => { resetAsyncForm() }, [resetAsyncForm]) return (
{})}> { reset( { firstName: "bill", }, { keepErrors: true, keepDirty: true, } ) }} />
) } ``` **Controller** **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) ```tsx import { useForm, Controller } from "react-hook-form" import { TextField } from "@mui/material" interface IFormInputs { firstName: string lastName: string } export default function App() { const { register, handleSubmit, reset, setValue, control } = useForm() const onSubmit = (data: IFormInputs) => console.log(data) return (
} name="firstName" control={control} rules={{ required: true }} defaultValue="" /> } name="lastName" control={control} defaultValue="" /> reset()} /> { reset({ firstName: "bill", lastName: "luo", }) }} /> ) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-controller-5h1q5) ```javascript import { useForm, Controller } from "react-hook-form" import { TextField } from "@mui/material" export default function App() { const { register, handleSubmit, reset, setValue, control } = useForm() const onSubmit = (data) => console.log(data) return (
} name="firstName" control={control} rules={{ required: true }} defaultValue="" /> } name="lastName" control={control} defaultValue="" /> reset()} /> { reset({ firstName: "bill", lastName: "luo", }) }} /> ) } ``` **Submit with Reset** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-handlesubmit-with-reset-xu1zu) ```javascript import { useEffect } from "react" import { useForm, useFieldArray, Controller } from "react-hook-form" function App() { const { register, handleSubmit, reset, formState, formState: { isSubmitSuccessful }, } = useForm({ defaultValues: { something: "anything" } }) const onSubmit = (data) => { // It's recommended to reset in useEffect as execution order matters // reset({ ...data }) } useEffect(() => { if (formState.isSubmitSuccessful) { reset({ something: "" }) } }, [formState.isSubmitSuccessful, reset]) return (
) } ``` **Field Array** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-reset-usefieldarray-forked-kdh2s) ```javascript import { useEffect } from "react" import { useForm, useFieldArray, Controller } from "react-hook-form" function App() { const { register, control, handleSubmit, reset } = useForm({ defaultValues: { loadState: "unloaded", names: [{ firstName: "Bill", lastName: "Luo" }], }, }) const { fields, remove } = useFieldArray({ control, name: "names", }) useEffect(() => { reset({ names: [ { firstName: "Bob", lastName: "Actually", }, { firstName: "Jane", lastName: "Actually", }, ], }) }, [reset]) const onSubmit = (data) => console.log("data", data) return (
    {fields.map((item, index) => (
  • } name={`names.${index}.lastName`} control={control} />
  • ))}
) } ``` ### Video --- [Watch on YouTube](https://www.youtube.com/watch?v=qmCLBjyPwVk) ### Tips --- - For a "Discard changes" button, call `reset()` with no arguments. The form goes back to the last default values. - After a successful save, call `reset(savedData)` so the saved data becomes the new baseline and `isDirty` goes back to `false`. If you only want to move the dirty baseline and keep errors, touched fields, and submission state, use [`resetDefaultValues`](https://react-hook-form.com/docs/useform/resetdefaultvalues). - When the server sends fresh data while the user is editing, use `reset(newData, { keepDirtyValues: true })`. Fields the user changed keep their values, and the other fields are updated. - To load data once from an API, use `useForm({ values })` instead of `reset` in a `useEffect`. See [which option to use](https://react-hook-form.com/docs/useform#values). ### Troubleshooting --- #### `reset()` clears the form instead of going back to the loaded data **Why it happens:** `reset()` with no arguments goes back to the default values. If you loaded the data with `setValue`, the default values never changed, so the form is reset to the original empty values. **Fix:** Load the data with `reset(data)` or [`values`](https://react-hook-form.com/docs/useform#values). The loaded data then becomes the default values, and a later `reset()` returns to it. --- # resetDefaultValues > Update the baseline default values after async operations like form submission, preserving in-flight user edits and recomputing dirty state in React Hook Form. Source: https://react-hook-form.com/docs/useform/resetdefaultvalues ## `resetDefaultValues:` [UseFormResetDefaultValues](https://react-hook-form.com/ts#UseFormResetDefaultValues) _(since v7.77.0)_ Update `defaultValues` and recompute `dirtyFields`/`isDirty` against the new baseline without modifying the current form values. This is useful when a form disables submission while `!isDirty` — after a successful async submission you can advance the baseline to the submitted values so that only post-submit edits are considered dirty. ### Props --- | Name | | Type | Description | | --------- | ------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `values` | | `object` | The new default values to establish as the baseline. Recommended to provide the full object. | | `options` | `keepDirty` | `boolean` | When set to `true`, existing `dirtyFields` state is preserved as-is rather than recomputed against the new baseline. | | | `keepIsValid` | `boolean` | When set to `true`, validation is not re-run after the baseline update and `isValid` remains unchanged. | > **Important: Rules** > > - Current form values (what the user has typed) are **never** modified by this method — only the internal baseline used to compute dirty state changes. > - `dirtyFields` and `isDirty` are recomputed against the new baseline unless `keepDirty` is set. > ### Examples --- **After Async Submission** **TS** ```tsx import { useForm } from "react-hook-form" interface FormValues { firstName: string lastName: string } export default function App() { const { register, handleSubmit, resetDefaultValues, formState: { isDirty }, } = useForm({ defaultValues: { firstName: "", lastName: "" }, }) const onSubmit = async (data: FormValues) => { await saveToServer(data) // Advance the baseline to the submitted values. // isDirty will now only be true if the user edits after this point. resetDefaultValues(data) } return (
) } ``` **JS** ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit, resetDefaultValues, formState: { isDirty }, } = useForm({ defaultValues: { firstName: "", lastName: "" }, }) const onSubmit = async (data) => { await saveToServer(data) // Advance the baseline to the submitted values. // isDirty will now only be true if the user edits after this point. resetDefaultValues(data) } return (
) } ``` **With Options** ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, resetDefaultValues } = useForm({ defaultValues: { firstName: "", lastName: "" }, }) const handleServerUpdate = (serverValues) => { resetDefaultValues(serverValues, { keepDirty: true, // preserve existing dirty tracking keepIsValid: true, // skip re-validation }) } return (
) } ``` ### Tips --- - Use `resetDefaultValues` for an autosave form. After each save, move the baseline to the saved values, so `isDirty` shows only the changes that have not been saved yet. The user can keep typing, and the inputs are not touched. - Pass the values that were actually saved, for example the server response, and not the current form values. If the user typed while the request was in flight, those changes then stay dirty. - To also clear errors, touched fields, and submission state, use [`reset`](https://react-hook-form.com/docs/useform/reset) instead. ### Troubleshooting --- #### The inputs do not change after `resetDefaultValues` **Why it happens:** This method changes only the baseline used for dirty comparison. It deliberately preserves the current values so edits made while a save request is in flight are not lost. **Fix:** Use [`reset(values)`](https://react-hook-form.com/docs/useform/reset) when you want to replace both the current values and the default values. Use `resetDefaultValues(values)` only when the inputs should stay untouched. #### `isDirty` is still `true` after a successful save **Why it happens:** The current values differ from the new baseline. This commonly happens when the user types while the request is in flight, or when only part of the saved object is passed to `resetDefaultValues`. **Fix:** Pass the complete values that the server actually saved. If the user made newer edits during the request, leave `isDirty` as `true`—those edits have not been saved yet. ### Related --- - [reset](https://react-hook-form.com/docs/useform/reset) - [resetField](https://react-hook-form.com/docs/useform/resetfield) --- # resetField > Reset a single field's value and state — errors, dirty, and touched — independently without resetting the entire React Hook Form. Source: https://react-hook-form.com/docs/useform/resetfield ## `resetField:` [UseFormResetField](https://react-hook-form.com/ts#UseFormResetField) Reset an individual field state. ### Props --- After invoking this function, with default options: - `isValid` will be reevaluated, unless `keepError: true` is passed. - `isDirty` will be reevaluated, unless `keepDirty: true` is passed. `ResetField` has the ability to retain field state. Here are the options you may want to use: | Name | | Type | Description | | ------- | -------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | | `string` | registered field name. | | options | `keepError` | `boolean` | When set to `true`, field error will be retained. | | | `keepDirty` | `boolean` | When set to `true`, `dirtyFields` will be retained. | | | `keepTouched` | `boolean` | When set to `true`, `touchedFields` state will be unchanged. | | | `defaultValue` | `unknown` | When this value is **not** provided, field will be revert back to it's defaultValue.
When this value is provided:
  • field will be updated with the supplied value
  • field's `defaultValue` will be updated to this value.
  • Only support non undefined value.
| > **Important: Rules** > > - name need to match registered field name. > > ```javascript > register("test") > resetField("test") // ✅ register input and resetField works > resetField("non-existent-name") // ❌ failed by input not found > ``` > ### Examples --- **Reset Field State** [Open in CodeSandbox](https://codesandbox.io/s/priceless-firefly-d0kuv) ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, resetField, formState: { isDirty, isValid }, } = useForm({ mode: "onChange", defaultValues: { firstName: "", }, }) const handleClick = () => resetField("firstName") return (

{isDirty && "dirty"}

{isValid && "valid"}

) } ``` **Reset With Options** [Open in CodeSandbox](https://codesandbox.io/s/resetfield-with-options-iw4wd) ```javascript import { useForm } from "react-hook-form" export default function App() { const { register, resetField, formState: { isDirty, isValid, errors, touchedFields, dirtyFields }, } = useForm({ mode: "onChange", defaultValues: { firstName: "", }, }) return (

isDirty: {isDirty && "dirty"}

touchedFields: {touchedFields.firstName && "touched field"}

dirtyFields:{dirtyFields.firstName && "dirty field"}

isValid: {isValid && "valid"}

error: {errors.firstName && "error"}


) } ``` ### Video --- The following video tutorial demonstrates `resetField` API. [Watch on YouTube](https://www.youtube.com/watch?v=IdLFcNaEFEo) ### Tips --- - Use `resetField` for a per-field "Undo" or "Cancel" button in an inline editor. Only that field's value and state change. - After you save one field, call `resetField(name, { defaultValue: savedValue })`. The saved value becomes the new default, so the field is no longer dirty. - To reset many fields at the same time, use [`reset`](https://react-hook-form.com/docs/useform/reset) with the `keep*` options. One call is easier to follow than many `resetField` calls. ### Troubleshooting --- #### `resetField` goes back to an empty value instead of the saved one **Why it happens:** `resetField` restores the field's default value. If you loaded or saved the value with `setValue`, the default value never changed. **Fix:** Pass the saved value as the new default: `resetField("name", { defaultValue: savedValue })`. To load data for the whole form, use [`values`](https://react-hook-form.com/docs/useform#values) or [`reset(data)`](https://react-hook-form.com/docs/useform/reset). --- # setError > Manually set a validation error on one or multiple fields, with support for server-side and custom errors in React Hook Form. Source: https://react-hook-form.com/docs/useform/seterror ## `setError:` [UseFormSetError](https://react-hook-form.com/ts#UseFormSetError) This function allows you to manually set an error on a field. You can call it multiple times to set errors on multiple fields. ### Props --- | Name | Type | Description | | ------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | input's name. | | `error` | `{ type?: string, message?: string, types?: MultipleFieldErrors }` | **`type`** _(optional)_ — An identifier for the error source (e.g. `"required"`, `"custom"`, `"serverError"`). Exposed as `errors[name].type`.

**`message`** _(optional)_ — The human-readable error message. Exposed as `errors[name].message`.

**`types`** _(optional)_ — A `Record` that assigns multiple messages to a single field, keyed by error type (e.g. `{ required: "This is required", minLength: "Too short" }`). Exposed as `errors[name].types`. Use this instead of `message` when you need to display more than one validation message for the same field simultaneously — set `criteriaMode: "all"` on the form if you also want built-in/schema validation to populate `types` the same way. | | options | `{ shouldFocus?: boolean }` | Should focus the input during setting an error. This only works when the input's reference is registered, it will not work for custom register as well. | > **Important: Rules** > > - This method will not persist the associated input error if the input passes `register`'s associated rules. > ```javascript > register("registerInput", { minLength: 4 }) > setError("registerInput", { type: "custom", message: "custom message" }) > // validation will pass as long as minLength requirement pass > ``` > - An error that is not associated with an input field will be persisted until cleared with `clearErrors`. This behavior is only applicable for built-in validation at the field level. > ```javascript > setError("notRegisteredInput", { type: "custom", message: "custom message" }) > // clearErrors() needs to be invoked manually to remove that custom error > ``` > - _(since v7.43.0)_ You can set a server or global error with `root` as > the key. This type of error will not persist with each submission. > > ```javascript > setError("root.serverError", { > type: "400", > }) > ``` > > - `shouldFocus` doesn't work when an input has been disabled. > - This method will force formState.isValid to false. > However, isValid is always derived from the validation results of your > registered inputs or schema. > - Avoid using `type`, `root`, `ref`, `types`, `message`, or `form` as field names — these collide with the internal shape of `FieldError`/`GlobalError`. > ### Examples --- **Single Error** **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-ts-seterror-nfxxu) ```tsx import { useEffect } from "react" import { useForm } from "react-hook-form" type FormInputs = { username: string } const App = () => { const { register, handleSubmit, setError, formState: { errors }, } = useForm() const onSubmit = (data: FormInputs) => { console.log(data) } useEffect(() => { setError("username", { type: "manual", message: "Dont Forget Your Username Should Be Cool!", }) }, [setError]) return (
{errors.username &&

{errors.username.message}

}
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-seterror-btbf8) ```javascript import { useForm } from "react-hook-form" const App = () => { const { register, setError, formState: { errors }, } = useForm() return (
{errors.test &&

{errors.test.message}

}
) } ``` **Multiple Errors** `setError` sets exactly one error per call. To set errors on multiple fields, call it once per field — typically in a loop over the server's error response. **TS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-ts-seterror-8h440) ```tsx import { useForm } from "react-hook-form" type FormInputs = { username: string firstName: string } const App = () => { const { register, handleSubmit, setError, formState: { errors }, } = useForm() const onSubmit = (data: FormInputs) => { console.log(data) } return (
{errors.username &&

{errors.username.message}

} {errors.firstName &&

{errors.firstName.message}

}
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-seterror-3y1op) ```javascript import { useForm } from "react-hook-form" const App = () => { const { register, handleSubmit, setError, formState: { errors }, } = useForm() const onSubmit = (data) => { console.log(data) } return (
{errors.username &&

{errors.username.message}

} {errors.firstName &&

{errors.firstName.message}

}
) } ``` **Single Field Errors** Use `types` (with `criteriaMode: "all"`) to attach multiple validation messages to a single field at the same time. Each key in the object is an error-type identifier; each value is the message to display for that rule. **TS** ```tsx import { useEffect } from "react" import { useForm } from "react-hook-form" type FormInputs = { lastName: string } const App = () => { const { register, handleSubmit, setError, formState: { errors }, } = useForm({ criteriaMode: "all", }) const onSubmit = (data: FormInputs) => console.log(data) useEffect(() => { setError("lastName", { types: { required: "This is required", minLength: "This is minLength", }, }) }, [setError]) return (
{errors.lastName && errors.lastName.types && (

{errors.lastName.types.required}

)} {errors.lastName && errors.lastName.types && (

{errors.lastName.types.minLength}

)}
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/seterror-single-field-errors-79wcr9) ```javascript import { useEffect } from "react" import { useForm } from "react-hook-form" const App = () => { const { register, handleSubmit, setError, formState: { errors }, } = useForm({ criteriaMode: "all", }) const onSubmit = (data) => { console.log(data) } useEffect(() => { setError("lastName", { types: { required: "This is required", minLength: "This is minLength", }, }) }, [setError]) return (
{errors.lastName && errors.lastName.types && (

{errors.lastName.types.required}

)} {errors.lastName && errors.lastName.types && (

{errors.lastName.types.minLength}

)}
) } ``` **Server Error** ```javascript import { useForm } from "react-hook-form"; const App = () => { const { register, handleSubmit, setError, formState: { errors } } = useForm({ criteriaMode: 'all', }); const onSubmit = async () => { const response = await fetch(...) if (response.status >= 400) { setError('root.serverError', { type: String(response.status), }) } } return (
{errors.root?.serverError?.type === "400" &&

server response message

}
); }; ``` ### Video --- The following video explains the `setError` API in detail. [Watch on YouTube](https://www.youtube.com/watch?v=raMqvE0YyIY) ### Tips --- - Map field errors from your API onto the form, and focus the first one: ```javascript const onSubmit = async (data) => { const response = await save(data) if (!response.ok) { const { fieldErrors } = await response.json() // e.g. { email: "Already taken" } Object.entries(fieldErrors).forEach(([name, message], index) => { setError( name, { type: "server", message }, { shouldFocus: index === 0 } ) }) } } ``` - Use `root.*` for errors that do not belong to one field, such as "Network error" or "Too many attempts". Root errors are cleared on the next submission. Show them with [`ErrorMessage`](https://react-hook-form.com/docs/useformstate/errormessage) and `name="root.server"`. - Give server errors a `type` such as `"server"`. Then your UI can show them differently from client-side validation errors. ### Troubleshooting --- #### An error set with `setError` disappears on submit and doesn't stop `onSubmit` **Why it happens:** `setError` adds an error to the form state, but it does not add a validation rule. On submit, `handleSubmit` validates the form again and clears errors that are not backed by a rule, including `root.*` errors. If every field passes, your `onSubmit` runs. **Fix:** Use `setError` to show errors that come back from the server after a submit. For errors that must block submission, add the check as a validation rule instead: ```javascript register("username", { validate: async (value) => (await isUsernameFree(value)) || "This username is taken", }) ``` --- # setFocus > Programmatically focus any registered input field, with an option to also select its current value in React Hook Form. Source: https://react-hook-form.com/docs/useform/setfocus ## `setFocus:` [UseFormSetFocus](https://react-hook-form.com/ts#UseFormSetFocus) This method will allow users to programmatically focus on input. Make sure input's ref is registered into the hook form. ### Props --- | Name | | Type | Description | | --------- | -------------- | ---------------------------- | ------------------------------------------------------------------------ | | `name` | | `string` | An input field name to focus | | `options` | `shouldSelect` | `boolean` | _(since v7.27.0)_ Whether to select the input content on focus. | > **Important: Rules** > > - This API will invoke focus method from the ref, so it's important to provide `ref` during `register`. > - Avoid calling `setFocus` right after `reset` as all input references will be removed by `reset` API. > ### Examples --- **TS** [Open in CodeSandbox](https://codesandbox.io/s/setfocus-rolus) ```tsx import { useEffect } from "react" import { useForm } from "react-hook-form" type FormValues = { firstName: string } export default function App() { const { register, handleSubmit, setFocus } = useForm() const onSubmit = (data: FormValues) => console.log(data) useEffect(() => { setFocus("firstName") }, [setFocus]) return (
) } ``` **JS** [Open in CodeSandbox](https://codesandbox.io/s/setfocus-rolus) ```javascript import { useEffect } from "react" import { useForm } from "react-hook-form" export default function App() { const { register, handleSubmit, setFocus } = useForm() const onSubmit = (data) => console.log(data) useEffect(() => { setFocus("firstName") }, [setFocus]) return (
) } ``` ### Tips --- - Focus the first field when the form opens: ```javascript useEffect(() => { setFocus("firstName") }, [setFocus]) ``` - You do not need `setFocus` to focus the first invalid field on submit. [`shouldFocusError`](https://react-hook-form.com/docs/useform#shouldFocusError) does this by default. - For a component that does not forward a DOM ref, give `field.ref` an object with a `focus` method. See the Tips section of [useController](https://react-hook-form.com/docs/usecontroller). ### Troubleshooting --- #### `setFocus` does nothing **Why it happens:** React Hook Form can only focus a mounted field whose DOM ref was received through `register` or `field.ref`. A custom input that drops the ref, or a field that is not currently rendered, has no focusable element. **Fix:** Forward the ref to the actual input. With `Controller`, pass `field.ref` to the component's ref prop (for example, `inputRef`), and call `setFocus` only after the field is mounted. #### Focusing immediately after `reset` does not work **Why it happens:** `reset` updates the form and its field references. In the same call stack, the target input may not have registered its ref again yet. **Fix:** Focus after React has committed the reset, for example from an effect that runs when the reset state changes. Avoid calling `reset()` and `setFocus()` back-to-back. --- # setValue > Dynamically update a registered field's value with options to trigger validation, mark the field dirty, or set it as touched. Source: https://react-hook-form.com/docs/useform/setvalue ## `setValue:` [UseFormSetValue](https://react-hook-form.com/ts#UseFormSetValue) This function allows you to dynamically set the value of a registered field and provides options to validate and update the form state. At the same time, it attempts to avoid unnecessary re-renders. ### Props --- | Name | | Description | | ---------------------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name`
`string` | | Target a single field or field array by name. | | `value`
`unknown` | | The value for the field. This argument is required and cannot be `undefined`. | | `options` | `shouldValidate`
`boolean` |
  • Whether to compute if your input is valid or not (subscribed to `errors`).
  • Whether to compute if your entire form is valid or not (subscribed to `isValid`).
  • This option only recomputes validity for the specified field, not the entire form's `errors`.
| | | `shouldDirty`
`boolean` |
  • Whether to compute if your input is dirty or not against your `defaultValues` (subscribed to `dirtyFields`).
  • Whether to compute if your entire form is dirty or not against your `defaultValues` (subscribed to `isDirty`).
  • This option will update `dirtyFields` at the specified field level, not the entire form's dirty fields.
| | | `shouldTouch`
`boolean` | _(since v7.8.0)_ Whether to set the input itself to be touched. | | | `delayError`
`boolean` | _(since v7.82.0)_ Opt-in flag that delays the display of the resulting validation error, using the delay (in milliseconds) configured via [`useForm({ delayError })`](https://react-hook-form.com/docs/useform#delayError). Only takes effect when `shouldValidate` is also set to `true`. | > **Important: Rules** > > - By default, `setValue` only updates the value and notifies [`watch`](https://react-hook-form.com/docs/useform/watch), [`useWatch`](https://react-hook-form.com/docs/usewatch) and [`subscribe`](https://react-hook-form.com/docs/useform/subscribe). It does **not** validate the field (even after the form has been submitted) or mark it as dirty or touched. Pass the options you need: > > ```javascript > setValue("firstName", "Bill", { > shouldValidate: true, // update errors and isValid > shouldDirty: true, // update dirtyFields and isDirty > shouldTouch: true, // update touchedFields > }) > ``` > > - `shouldDirty` only guarantees that the target field is marked in `dirtyFields` immediately. Because `isDirty` always compares current values against `defaultValues`, a later update to _any_ field can trigger a `dirtyFields` recompute that also surfaces other fields whose value already differs from their default — including ones last written with `shouldDirty: false`. > > - You can use methods such as [replace](https://react-hook-form.com/docs/usefieldarray#return) or [update](https://react-hook-form.com/docs/usefieldarray#return) for a field array; however, they will cause the component to unmount and remount for the targeted field array. > > ```javascript > const { update } = useFieldArray({ name: "array" }) > > // unmount fields and remount with updated value > update(0, { test: "1", test1: "2" }) > > // will directly update input value > setValue("array.0.test1", "1") > setValue("array.0.test2", "2") > ``` > > - It's recommended to target the field's name rather than make the second argument a nested object. > > ```javascript > setValue("yourDetails.firstName", "value") // ✅ performant > setValue("yourDetails", { firstName: "value" }) ❌ // less performant > > register("nestedValue", { value: { test: "data" } }) // register a nested value input > setValue("nestedValue.test", "updatedData") // ❌ failed to find the relevant field > setValue("nestedValue", { test: "updatedData" }) // ✅ setValue finds the input and updates it > ``` > > - It's recommended to register the input's name before invoking `setValue`. To update the entire `FieldArray`, make sure the `useFieldArray` hook is being executed first. > > **Important:** Prefer `replace` from `useFieldArray` for updating an entire field array — it's the more explicit, purpose-built API, and this `setValue` usage may become discouraged in a future version. > > ```javascript > // you can update an entire Field Array, > setValue("fieldArray", [{ test: "1" }, { test: "2" }]) // ⚠️ works, but prefer replace() from useFieldArray > > // you can use `setValue` on an unregistered input > setValue("notRegisteredInput", "value") // ✅ prefer it to be registered > > // the following will implicitly register a single input (without register being invoked) > setValue("resultSingleNestedField", { test: "1", test2: "2" }) // ⚠️ works, but registers a field you never called register() on — prefer registering it explicitly > > // With registered inputs, `setValue` will update both inputs correctly. > register("notRegisteredInput.test") > register("notRegisteredInput.test2") > setValue("notRegisteredInput", { test: "1", test2: "2" }) // ✅ sugar syntax to setValue twice > ``` > ### Examples --- **Basic** [Open in CodeSandbox](https://codesandbox.io/s/react-hook-form-v7-ts-setvalue-8z9hx) ```javascript import { useForm } from "react-hook-form" const App = () => { const { register, setValue } = useForm({ defaultValues: { firstName: "", }, }) return (
) } ``` **Delay Error** ```javascript // the actual delay (in ms) is configured once at the form level const { setValue } = useForm({ delayError: 500 }) setValue("firstName", "Bill", { delayError: true, // opt in to the 500ms delay configured above shouldValidate: true, }) ``` **Dependent Fields** [Open in CodeSandbox](https://codesandbox.io/s/dependent-field-dwin1) ```tsx import { useEffect } from "react" import { useForm } from "react-hook-form" type FormValues = { a: string b: string c: string } export default function App() { const { watch, register, handleSubmit, setValue, formState } = useForm({ defaultValues: { a: "", b: "", c: "", }, }) const onSubmit = (data: FormValues) => console.log(data) const [a, b] = watch(["a", "b"]) useEffect(() => { if (formState.touchedFields.a && formState.touchedFields.b && a && b) { setValue("c", `${a} ${b}`) } }, [setValue, a, b, formState]) return (
) } ``` ### Video --- [Watch on YouTube](https://www.youtube.com/watch?v=qpv51sCH3fI) ### Tips --- - When a value comes from the user through a custom widget, such as a map picker or a rich-text editor, pass `{ shouldDirty: true, shouldTouch: true, shouldValidate: true }`. The field then behaves the same as a native input that the user typed in. - To update several fields at once, use [`setValues`](https://react-hook-form.com/docs/useform/setvalues). It updates them with a single re-render, while calling `setValue` many times can cause more renders. - Do not call `setValue` during render. Call it in an event handler or an effect. ### Troubleshooting --- #### `isDirty` and errors don't change after `setValue` **Why it happens:** By default, `setValue` only updates the value. It does not validate the field or mark it as dirty or touched. **Fix:** Pass the options you need: ```javascript setValue("email", value, { shouldValidate: true, shouldDirty: true, shouldTouch: true, }) ``` --- # setValues > Update multiple React Hook Form field values at once using an object or a callback that receives the current form values and returns changes. Source: https://react-hook-form.com/docs/useform/setvalues ## `setValues:` [UseFormSetValues](https://react-hook-form.com/ts#UseFormSetValues) _(since v7.74.0)_ This function allows you to dynamically set multiple field values at once and have the options to validate and update the form state. It also accepts a callback function that receives the current form values, making it easy to derive the next state from the existing one. ### Props --- | Name | | Description | | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `value`
Partial\ \| (formValues: TFieldValues) => TFieldValues | | An object containing the field values to update, or a callback function that receives the current form values and returns the next form values. This argument is required. | | `options` | `shouldValidate`
`boolean` |
  • Whether to compute if your input is valid or not (subscribed to `errors`).
  • Whether to compute if your entire form is valid or not (subscribed to `isValid`).
| | | `shouldDirty`
`boolean` |
  • Whether to compute if your input is dirty or not against your `defaultValues` (subscribed to `dirtyFields`).
  • Whether to compute if your entire form is dirty or not against your `defaultValues` (subscribed to `isDirty`).
| | | `shouldTouch`
`boolean` | Whether to set the updated inputs to be touched. | | | `delayError`
`boolean` | _(since v7.82.0)_ Opt-in flag that delays the display of the resulting validation error, using the delay (in milliseconds) configured via [`useForm({ delayError })`](https://react-hook-form.com/docs/useform#delayError). Only takes effect when `shouldValidate` is also set to `true`. | > **Important: Rules** > > - When using the callback form, the function receives a snapshot of the current form values and should return the next form values. > > - This method does not reset the form. Use [`reset`](https://react-hook-form.com/docs/useform/reset) if you need to reinitialize `defaultValues`. > > - Unlike calling [`setValue`](https://react-hook-form.com/docs/useform/setvalue) multiple times in sequence, `setValues` batches all updates into a single re-render. > ### Examples --- **Basic** ```javascript import { useForm } from "react-hook-form" const App = () => { const { register, setValues } = useForm({ defaultValues: { firstName: "", lastName: "", }, }) return (
) } ``` **Callback (derive next state from current values)** ```javascript import { useForm } from "react-hook-form" const App = () => { const { register, setValues } = useForm({ defaultValues: { name: "", count: 0, }, }) return (
) } ``` **With options** ```javascript import { useForm } from "react-hook-form" const App = () => { const { register, setValues } = useForm({ defaultValues: { firstName: "", lastName: "", }, }) return (
) } ``` ### Tips --- - Top-level keys are merged shallowly. `setValues({ address: { city: "Paris" } })` replaces the whole `address` object, so `address.street` is lost. To change one nested value, spread the current values in the callback form: ```javascript setValues((values) => ({ ...values, address: { ...values.address, city: "Paris" }, })) ``` - Use `setValues` to fill a form from a template or a previous entry, so the user can still see what changed. If the data should become the new defaults, use [`reset`](https://react-hook-form.com/docs/useform/reset). ### Troubleshooting --- #### A nested sibling value disappears after `setValues` **Why it happens:** Top-level keys are merged shallowly. Updating `{ address: { city: "Paris" } }` replaces the complete `address` object rather than merging its nested properties. **Fix:** Use the callback form and preserve the nested values you are not changing: ```javascript setValues((values) => ({ ...values, address: { ...values.address, city: "Paris" }, })) ``` For one nested field, [`setValue("address.city", "Paris")`](https://react-hook-form.com/docs/useform/setvalue) is simpler. #### Errors, touched fields, or dirty state do not change **Why it happens:** `setValues` updates values, but validation and form-state updates are opt-in so a batch update does not do extra work by default. **Fix:** Pass the state updates you need: ```javascript setValues(values, { shouldValidate: true, shouldDirty: true, shouldTouch: true, }) ``` --- # subscribe > Subscribe to React Hook Form state changes outside the render cycle — ideal for analytics, side effects, and non-React integrations. Source: https://react-hook-form.com/docs/useform/subscribe ## `subscribe:` [UseFormSubscribe](https://react-hook-form.com/ts#UseFormSubscribe) _(since v7.55.0)_ Subscribe to [`formState`](https://react-hook-form.com/docs/useform/formstate) changes and value updates. You can subscribe to individual fields or the entire form, while avoiding unnecessary re-renders caused by form changes. ### Props --- | Name | Type | Description | Example | | --------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | name | `undefined` | Subscribe to the entire form | `subscribe({ callback })` | | | `string` | Subscribe to a single field by **name**. | `subscribe({ name: 'firstName' })` | | | `string[]` | Subscribe to multiple fields by **name**. | `subscribe({ name: ['firstName', 'lastName'] })` | | formState | `Partial` | Pick which [`formState`](https://react-hook-form.com/docs/useform/formstate) to subscribe to. |
subscribe({ 
formState: {
values: true,
isDirty: true,
dirtyFields: true,
touchedFields: true,
isValid: true,
errors: true,
validatingFields: true,
isValidating: true
}
})
| | callback | `Function` | Runs whenever any of the picked `formState` changes. It receives the full form state, plus `values` (the latest form values), `name` (the field that changed, if any) and `type` (the event, such as `change` or `blur`). |
subscribe({ 
formState: {
values: true
},
callback: ({ values }) => {
console.log(values)
}
})
| | exact | `boolean = false` | Enable exact name matching. When `false` (default), the subscription fires when the subscribed name is a prefix of the changed field name, or vice versa. _(since v7.81.0)_ When `true`, it fires when the subscribed field itself or one of its ancestor paths is updated, but not when a nested child path changes (for example, `"users.0.name"` is updated when `"users"` is set, while `"users"` is not updated when `"users.0.name"` changes). | `subscribe({ name: 'target', exact: true })` | ### Return --- | Type | Description | | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `() => void` | A function that ends the subscription. Call it when the component unmounts, for example by returning it from `useEffect`. | > **Important: Notes** > > - This function shares the same functionality as `createFormControl.subscribe`, with the key difference being that [createFormControl](https://react-hook-form.com/docs/createFormControl) can be initialized outside of a React component. > - This function is dedicated to subscribing to form state without **render**, use this function for that instead of [watch](https://react-hook-form.com/docs/useform/watch) callback function. > ### Examples --- ```tsx import { useEffect } from "react" import { useForm } from "react-hook-form" type FormInputs = { firstName: string lastName: string } export default function App() { const { register, subscribe } = useForm() useEffect(() => { // make sure to unsubscribe; const callback = subscribe({ formState: { values: true, }, callback: ({ values }) => { console.log(values) }, }) return () => callback() // You can also just return the subscribe // return subscribe({ callback: ({ values }) => console.log(values) }); }, [subscribe]) return (
) } ``` **Autosave a draft** Because `subscribe` doesn't re-render, it suits side effects like saving a draft while the user types: ```tsx import { useEffect } from "react" import { useForm } from "react-hook-form" type FormValues = { title: string; body: string } export default function App() { const { register, subscribe } = useForm({ defaultValues: { title: "", body: "" }, }) useEffect(() => { let timer: ReturnType const unsubscribe = subscribe({ formState: { values: true }, callback: ({ values }) => { clearTimeout(timer) timer = setTimeout(() => { localStorage.setItem("draft", JSON.stringify(values)) }, 500) }, }) return () => { clearTimeout(timer) unsubscribe() } }, [subscribe]) return (