Language: JavaScript
Form Handling
React Hook Form was created by Bill Luo to simplify form management in React applications. It focuses on minimizing boilerplate, reducing unnecessary re-renders, and providing easy integration with validation libraries like Yup and Zod.
React Hook Form is a performant, flexible, and easy-to-use library for managing forms in React. It leverages uncontrolled components and React hooks to reduce re-renders and improve form performance.
npm install react-hook-formyarn add react-hook-formReact Hook Form uses the `useForm` hook to handle form state and validation. Inputs are registered via the `register` function, and submission is handled with `handleSubmit`. It supports synchronous and asynchronous validation, form resetting, error tracking, and custom input components.
import { useForm } from 'react-hook-form';
function MyForm() {
const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('firstName')} placeholder='First Name' />
<input {...register('lastName')} placeholder='Last Name' />
<button type='submit'>Submit</button>
</form>
);
}Defines a basic form with two fields, registering them with `useForm` and logging the submitted data.
const { register, handleSubmit, formState: { errors } } = useForm();
<input {...register('email', { required: true })} placeholder='Email' />
{errors.email && <span>Email is required</span>}Adds simple required validation to a field and displays an error message if validation fails.
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
const schema = yup.object({ email: yup.string().email().required() });
const { register, handleSubmit, formState: { errors } } = useForm({ resolver: yupResolver(schema) });Integrates React Hook Form with Yup schema validation for more complex rules.
const CustomInput = ({ register, name }) => <input {...register(name)} />;
<CustomInput register={register} name='username' />Demonstrates how to use custom input components with React Hook Form by forwarding the `register` function.
const { fields, append, remove } = useFieldArray({ control, name: 'friends' });
fields.map((field, index) => <input {...register(`friends.${index}.name`)} />);Manages dynamic arrays of input fields with `useFieldArray`.
Use uncontrolled components for better performance.
Leverage schema validation libraries like Yup or Zod for complex forms.
Use `useFieldArray` for dynamic fields.
Keep error messages user-friendly and accessible.
Reset forms using `reset()` when needed, especially after submission.