React Hook Form is a small, dependency-free library for building forms in React. It registers inputs without turning each keystroke into a re-render, handles validation with built-in rules or schema libraries like Zod and Yup, and gives you form state such as errors, dirty and touched fields. In this guide, we cover setup, validation, UI library integration, TypeScript, performance, and when React 19's built-in form actions are enough on their own.
#What is React Hook Form
Most applications have forms to collect data, depending on the use case, implementing forms can be pretty complex, especially when building enterprise-level applications that provide an intuitive and flawless user experience. As a developer, it is highly likely that you have stumbled across building forms in most of your projects. Of course, you can manage simple forms on your own but after a point, it becomes sensible to use a library that abstracts a lot of work involved in handling complex forms.
React Hook Form is one such library that helps to manage complex forms. It comes with great performance, is super lightweight, has zero dependencies, can be easily integrated with different React UI frameworks like Material, Antd, and provides an intuitive API and excellent developer experience.
#How to use React Hook Form
To get started, install the library:
npm install react-hook-form
Using it inside your component is super simple, import the useForm hook from the library
import { useForm } from "react-hook-form";
The useForm hook gives us access to many properties, for now, we will only use register and handleSubmit. Inside your functional component destructure them
const { register, handleSubmit } = useForm();
Register an input element with a variable name like this, this will make the value of input available for form validation and form submission.
<inputclassName="border-2 outline-none p-2 rounded-md"placeholder="Name"{...register("name")}/>
Then you can handle your submit your form this way, and can create an onSubmit method which will have access to the forms data.
<form onSubmit={handleSubmit(onSubmit)}>
Below is a complete example
import { useState } from "react";import { useForm } from "react-hook-form";export default function ReactHookFormMini() {const { register, handleSubmit } = useForm();const [data, setData] = useState("");const onSubmit = (data) => {setData(data)}return (<div className="w-full flex justify-center items-center bg-gray-900 p-8 border-r border-dashed"><div className="w-1/2 shadow-lg rounded-md bg-white p-8 flex flex-col" style={{height:'375px'}}><h2 className="text-center font-medium text-2xl mb-4">React Hook Form Basic</h2><formonSubmit={handleSubmit(onSubmit)}className="flex flex-1 flex-col justify-evenly"><inputclassName="border-2 outline-none p-2 rounded-md"placeholder="Name"{...register("name")}/><buttonclassName=" flex justify-center p-2 rounded-md w-1/2 self-center bg-gray-900 text-white hover:bg-gray-800"type='submit'><span>Submit</span></button></form><div className='h-4'><p> Data: {JSON.stringify(data)}</p></div></div></div>);}
This is how it will look, we have used tailwind for the css, feel free to use your own CSS frameworks.
#Adding validations
Validations are part and parcel of almost every form, they’re an application’s first line of defense against unwanted data. Validations ensure that incorrect data doesn’t reach the backend servers and eventually the databases. Ideally in most software data is validated at every layer i.e the Frontend, Backend, and Database.
For large forms, it can become tedious and repetitive to manage validations for each and every field and their error states. React Hook Form provides excellent API options and also aligns with the existing HTML standard for form validation, here is the list of validation rules supported by the library:
required- The input value is mandatory or notmin- The minimum value that can be acceptedmax- The maximum value that can be acceptedminLength- The minimum length of input that can be acceptedmaxLength- The maximum length of input that can be acceptedpattern- A regex pattern to validate the inputvalidate- Any custom function to validate the input
A simple example on how to use these attributes
<inputclassName="border-2 outline-none p-2 rounded-md"placeholder="Phone Number"{...register("phoneNumber", {minLength: 1,maxLength: 10,})}/>
Also, you can pass error messages with the validation rule, this will make displaying errors very simple.
<inputclassName="border-2 outline-none p-2 rounded-md"placeholder="Email"{...register("email", {pattern: {value: /^.*@hygraph.com$/,message: 'Email must end with hygraph.com'}})}/>
You can get the error object from useForm and then display the error message in the template.
const { formState: { errors } } = useForm();
<span className="text-sm text-red-700">{errors?.email?.message}</span>
#Schema validation libraries
React hook form also supports integration with well known schema validation libraries. You can use libraries like Zod, Joi, or Yup inside your forms along with React hook form. Let us check out an example with the Yup schema validation library.
First, we need to declare our form data schema as shown below
// ...const schema = yup.object({fullName: yup.string().required(),age: yup.number().positive().integer().required(),}).required();// ...
Then we can import the yup resolver from the @hookform/resolvers package, and pass it to the useForm method of React Hook Form.
import { yupResolver } from "@hookform/resolvers/yup";// ...const {register,handleSubmit,formState: { errors },} = useForm({resolver: yupResolver(schema),});// ...
Here is a complete example
import * as yup from "yup";import { yupResolver } from "@hookform/resolvers/yup";import { useForm } from "react-hook-form";const schema = yup.object({fullName: yup.string().required(),age: yup.number().positive().integer().required(),}).required();export default function YupExample() {const {register,handleSubmit,formState: { errors },} = useForm({resolver: yupResolver(schema),});const onSubmit = (data) => console.log(data);return (<form onSubmit={handleSubmit(onSubmit)}><input {...register("fullName")} /><p>{errors.fullName?.message}</p><input {...register("age")} /><p>{errors.age?.message}</p><input type="submit" /></form>);}
#Integrating with other components
It is possible that we have UI Frameworks already set up and are using UI components from that library, React Hook Form can integrate with those UI frameworks as well. In the below example you can find how to integrate React Hook Form with AntD’s input components.
import React, { useState } from 'react';import { Controller, useForm } from "react-hook-form";import { Input, Checkbox, Slider } from "antd";export default function RFHWithAntd() {const { control, handleSubmit } = useForm();const [data, setData] = useState({});const onSubmit = (data) => {setData(data)}return (<div className="w-full flex justify-center items-center bg-gray-900 p-8 border-r border-dashed"><div className="w-1/2 shadow-lg rounded-md bg-white p-8 flex flex-col" style={{ height: '375px' }}><h2 className="text-center font-medium text-2xl mb-4">React Hook Form With AntD</h2><formonSubmit={handleSubmit(onSubmit)}className="flex flex-1 flex-col justify-evenly"><Controllercontrol={control}name="name"render={({ field }) => (<Input{...field}placeholder="Name"/>)}/><div className="flex"><label>Is Developer?</label><Controllercontrol={control}name="isDeveloper"render={({ field: { value, onChange } }) => (<CheckboxclassName="ml-4"checked={value}onChange={(e) => {onChange(e.target.checked);}}/>)}/></div><section><label>Experience In Years</label><Controllercontrol={control}name="experience"render={({ field }) => <Slider {...field} />}/></section><buttonclassName=" flex justify-center p-2 rounded-md w-1/2self-center bg-gray-900 text-white hover:bg-gray-800"type='submit'><span>Submit</span></button></form><div className='h-4'><p> Data: {JSON.stringify(data)}</p></div></div></div>)};
#React Hook Form and React 19 form actions
React 19 added form features of its own. You can pass a function to a form's action prop, track the result and pending state with useActionState, and read the parent form's status from a child button with useFormStatus. For a simple form that sends a few fields to the server and shows one message back, that's often all you need:
import { useActionState } from "react";export default function NewsletterForm() {const [message, formAction, isPending] = useActionState(async (previousMessage, formData) => {const email = formData.get("email");if (!email.endsWith("@hygraph.com")) {return "Email must end with hygraph.com";}return `Subscribed ${email}`;},null);return (<form action={formAction}><input name="email" type="email" placeholder="Email" /><button type="submit" disabled={isPending}>Subscribe</button><p>{message}</p></form>);}
React Hook Form still earns its place when a form gets bigger: validation that runs while the user types, field-level state like dirty and touched, schema resolvers, fields that appear based on other answers, and large forms that must stay fast. The two also work together, since you can call your server action from React Hook Form's handleSubmit once client-side validation passes. React Hook Form v7 supports React 19.
If your project uses React Compiler, read watched values with the useWatch Hook instead of the watch function, because the compiler can memoize watch results and leave them stale:
import { useForm, useWatch } from "react-hook-form";const { register, control } = useForm();const isDeveloper = useWatch({ control, name: "isDeveloper" });
#React Hook Form examples
TypeScript
React hook form supports TypeScript which gives additional type safety to our code. We can define the types for our form data and pass it to React Hook Form as shown below
import { useForm } from "react-hook-form"type FormData = {firstName: stringage: number}export default function TypeScriptExample() {// ...const {register,setValue,handleSubmit,formState: { errors },} = useForm<FormData>()const onSubmit = handleSubmit((data) => console.log(data))return (// ...)}
That's it, now React Hook Form is now aware how our form data looks and it will try to prevent any type violations. For example, if we add the code below in the markup of the Typescript form, it will show us a type error saying property name does not exist on type FormData
return (// ...{errors.name?.message}// ...)
Comparing performance
We mentioned earlier that React Hook Form delivers great performance, one of the reasons for the same is how the library manages re-renders. It registers uncontrolled inputs and reads their values through refs instead of storing every keystroke in state. Compared to any other library or an implementation of a Form in React from scratch, React Hook Form hardly performs any re-renders when values inside your form change, which is a great optimization to have out of the box. We can go through an example to establish this, we will build two forms with the same functionality. One with implementation from scratch and another with React Hook Form, then compare the re-renders for the same input.
Normal form
import React, { useState } from 'react';let renderCount = 0export default function NormalForm() {const [name, setName] = useState('');const [email, setEmail] = useState('');const [showFormData, setShowFormData] = useState(false)const onSubmit = (event) => {event.preventDefault()setShowFormData(true)console.log('Run Validations Manually, maintain & show errors on UI, if all good make API call.')}renderCount += 1return (<div className="w-1/2 flex justify-center items-center bg-gray-900 p-8"><div className="w-full shadow-lg rounded-md bg-white p-8 flex flex-col" style={{ height: '375px' }}><h2 className="text-center font-medium text-2xl mb-4">Normal Form</h2>Render Count -- {renderCount}<formonSubmit={onSubmit}className="flex flex-1 flex-col justify-evenly"><inputclassName="border-2 outline-none p-2 rounded-md"placeholder="Name"value={name}onChange={(e) => { setName(e.target.value) }}/><inputclassName="border-2 outline-none p-2 rounded-md"type="email"placeholder="Email"value={email}onChange={(e) => { setEmail(e.target.value) }}/><buttonclassName=" flex justify-center p-2 rounded-mdw-1/2 self-center bg-gray-900 text-white hover:bg-gray-800"type='submit'><span>Submit</span></button></form>{<div className='h-4'><p> Data:{showFormData ?<span> {name} {email} </span>: null}</p></div>}</div></div>);}
React Hook Form
import { useState } from "react";import { useForm } from "react-hook-form";let renderCount = 0export default function ReactHookForm() {const { register, handleSubmit } = useForm();const [data, setData] = useState("");const onSubmit = (data) => {setData(JSON.stringify(data))}renderCount += 1return (<div className="w-1/2 flex justify-center items-center bg-gray-900 p-8 border-r border-dashed"><div className="w-full shadow-lg rounded-md bg-white p-8 flex flex-col" style={{ height: '375px' }}><h2 className="text-center font-medium text-2xl mb-4">React Hook Form</h2>Render Count -- {renderCount}<formonSubmit={handleSubmit(onSubmit)}className="flex flex-1 flex-col justify-evenly"><inputclassName="border-2 outline-none p-2 rounded-md"placeholder="Name"{...register("name")}/><inputclassName="border-2 outline-none p-2 rounded-md"placeholder="Email"{...register("email")}/><buttonclassName=" flex justify-center p-2 rounded-mdw-1/2 self-center bg-gray-900 text-white hover:bg-gray-800"type='submit'><span>Submit</span></button></form><div className='h-4'><p> Data: {data}</p></div></div></div>);}
At the start. without any insertions in the form.
After inserting the same values in the form and hitting submit.
React Hook Form took 4 re-renders while the normal form took 58, the difference is substantial. Also, this is a very simple form with two fields, so you can imagine that the re-renders in a complex form will be even more.
Advanced example
To strengthen our understanding, we can go one step further and explore the other available API options.
The useForm hook provides a formState property which gives us more details about the user’s interaction with our form.
isDirty: boolean value that denotes if the user interacted with the formisValid: boolean value that denotes if the current form state is valid.errors: an object that contains errors if any of the validations are failing.isSubmitted: boolean value that denotes if the user has tried to submit the form at least oncetouchedFields: an object which holds the touched fields.dirtyFields: an object which holds the dirty fields.
The difference between dirty and touched fields is that If the user clicks on a text input, it’s marked as touched but not dirty, after that, if the user also enters any value inside the text input then only it is marked as dirty.
The useForm hook also provides a watch function, which can be used to watch on form inputs and display other fields dynamically. Dynamic forms are a common use case, where form fields are shown dynamically based on what a user enters in previous fields.
Here’s a complete advanced example showing the use of all the above properties.
import { useState } from 'react';import { useForm } from 'react-hook-form';let renderCount = 0export default function ReactHookFormAdvanced() {const {register,handleSubmit,formState: { touchedFields, isDirty, isValid, dirtyFields, isSubmitted, errors },watch} = useForm();const [data, setData] = useState('');const watchIsDeveloper = watch('isDeveloper');renderCount += 1return (<div className='w-full flex justify-center items-center bg-gray-900 p-8'><div className='w-2/3 shadow-lg rounded-md bg-white p-8 flex flex-col justify-start' style={{ height: '700px' }}><h2 className='text-center font-medium text-2xl mb-4'>React Hook Form Advanced</h2>Render Count -- {renderCount}<formonSubmit={handleSubmit(setData)}className='flex flex-1 flex-col justify-evenly'><inputclassName='border-2 outline-none p-2 rounded-md'placeholder='Name'{...register('name')}/><inputclassName='border-2 outline-none p-2 rounded-md'placeholder='Email'{...register('email', { required: 'Email is required.' })}/><inputclassName='border-2 outline-none p-2 rounded-md'placeholder='Phone Number'{...register('phoneNumber')}/><div><span className='mr-4'>Are you a developer?</span><input type='checkbox' {...register('isDeveloper')} /></div>{watchIsDeveloper ?<div className='flex w-full '><inputclassName='flex-1 border-2 outline-none p-2 rounded-md mr-2'placeholder='Experience (Years)'{...register('exp_years')} /><inputclassName='flex-1 border-2 outline-none p-2 rounded-md'placeholder='Experience (Months)'{...register('exp_months')} /></div>: null}<buttonclassName=' flex justify-center p-2 rounded-mdw-1/2 self-center bg-gray-900 text-white hover:bg-gray-800'type='submit'><span>Submit</span></button></form><p className='w-4/5'> <strong> Data: </strong> {JSON.stringify(data)} </p><p> <strong> Is Valid: </strong> {JSON.stringify(isValid)}</p><p> <strong> Is Dirty : </strong> {JSON.stringify(isDirty)} </p><p> <strong> Is Submited: </strong> {JSON.stringify(isSubmitted)}</p><p> <strong> Errors: </strong> {JSON.stringify(errors?.email?.message)}</p><p> <strong> Dirty Fields : </strong> {JSON.stringify(dirtyFields)} </p><p> <strong> Touched Fields: </strong> {JSON.stringify(touchedFields)} </p><p> <strong> Watching Is Developer: </strong> {JSON.stringify(watchIsDeveloper)}</p></div></div>);}
#Using React Hook Form with an AI coding agent
Forms are how apps write content back: a review, a support request, a product update an editor submits from a custom tool. Once that data heads for a content API, the form's validation rules should match the model it lands in. With a typed schema, an AI coding agent can read the real fields, generate the matching Zod or Yup schema and wire handleSubmit to the right mutation, so client and backend agree on what valid data looks like. Hygraph, the agentic content platform and headless CMS, accepts those writes through GraphQL mutations, and its MCP server lets Claude Code or Cursor inspect your models and draft entries, with delete and unpublish blocked. To connect your forms and pages to structured content, start with building your React app on a headless CMS.
#Wrapping up
React Hook Form gives you fast, well-validated forms with very little code, and it works well alongside React 19's built-in form actions. Pick the built-in hooks for simple submissions and React Hook Form when validation and field state get complex. When you're ready to power those forms and the pages around them with structured content, see how Hygraph works with React.
Frequently Asked Questions
Building and validating forms in React with less code and fewer re-renders. The library registers inputs, tracks errors and dirty or touched fields, and hands you clean data on submit. It has no dependencies, works with UI libraries like MUI and AntD, and plugs into schema validators.
Reach for it once a form needs more than a submit handler: validation while the user types, conditional fields, many inputs or reusable schemas. For a simple form that posts a few values and shows one message, React 19's form actions and useActionState are often enough without an extra library.
For most production forms, yes. It's small, has zero dependencies and keeps inputs uncontrolled, so typing doesn't re-render the whole form. You also get a mature API for errors, field arrays and resolvers. The only real cost is one more dependency to keep updated.
Install zod and @hookform/resolvers, define a Zod schema for your fields, then pass zodResolver(schema) as the resolver option in useForm. Errors from the schema land in formState.errors, and with TypeScript you can infer the form's data type from the same schema, so types and validation never drift apart.
It does. React Hook Form v7 supports React 19, and you can call a server action from handleSubmit after client-side validation passes. If you use React Compiler, read watched values with the useWatch Hook rather than watch, so the compiler doesn't serve you a stale value.
Generate it from the model. When the fields your form writes to are defined in a typed schema, you or a coding agent can derive matching Zod or Yup rules from it. With a structured content platform like Hygraph, the GraphQL schema becomes that single source, so frontend and backend agree on valid data.
Blog Author