How does React Hook Form simplify building forms compared to managing every field with useState manually?
Short answer
React Hook Form lets you register each input once and handles tracking its value, validation, and errors internally, without causing your component to re render on every single keystroke like a manually controlled input often does.
Advertisement
AModel answer
React Hook Form lets you register each input once and handles tracking its value, validation, and errors internally, without causing your component to re render on every single keystroke like a manually controlled input often does. This makes forms both easier to write and noticeably faster, especially for forms with many fields.
import { useForm } from 'react-hook-form';
function SignupForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
function onSubmit(data) {
console.log(data);
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('email', { required: true })} />
{errors.email && <p>Email is required</p>}
<button type="submit">Sign Up</button>
</form>
);
}Real-world example
A job application form with twenty different fields uses React Hook Form to avoid slowing down as the user types, since it does not re render the entire form on every keystroke the way a fully manually controlled form would.
Likely follow-ups
- Why does React Hook Form avoid unnecessary re renders compared to a fully controlled approach?
- How would you add custom validation rules beyond simply marking a field as required?
Related topics