React Hook Form은 React 애플리케이션에서 폼 데이터를 관리하고 검증하는 데 최적화된 경량 라이브러리임. 폼을 제어하고 검증할 때 간단한 문법으로 React의 상태를 효율적으로 관리할 수 있음. 기존의 폼 라이브러리보다 성능이 뛰어나며, 특히 컨트롤되지 않는 폼(uncontrolled form) 요소를 사용할 때 더 빠르게 동작함.
React Hook Form은 구성 요소와 성능을 고려한 설계로 불필요한 리렌더링을 최소화하고, 가벼운 폼 관리를 가능하게 해줌.
npm install react-hook-form
yarn add react-hook-form
React Hook Form의 가장 기본적인 사용법은 useForm 훅을 사용하는 것임. useForm을 호출하면 여러 가지 유용한 기능을 포함한 객체를 반환함.
import React from 'react';
import { useForm } from 'react-hook-form';
function App() {
const { register, handleSubmit, formState: { errors } } = 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>
);
}
export default App;
React Hook Form은 기본적으로 HTML의 기본 검증 속성을 지원함. required, minLength, maxLength 등의 옵션을 추가해 폼 검증을 수행할 수 있음.
<input {...register("firstName", { required: true, minLength: 2 })} placeholder="First Name" />
{errors.firstName && <p>First name is required and must be at least 2 characters.</p>}
React Hook Form은 기본 입력 요소 외에도 체크박스, 라디오 버튼, 셀렉트와 같은 다양한 입력 유형을 지원함.
<input type="checkbox" {...register("acceptTerms", { required: true })} />
{errors.acceptTerms && <p>You must accept the terms and conditions.</p>}
<select {...register("gender", { required: true })}>
<option value="">Select...</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
{errors.gender && <p>Gender is required.</p>}
React Hook Form은 Yup과 같은 검증 라이브러리와의 통합을 통해 복잡한 검증 로직을 지원함. Yup을 사용해 스키마를 정의하고, 이를 resolver로 넘기면 검증 로직을 손쉽게 확장할 수 있음.
import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
const schema = yup.object().shape({
firstName: yup.string().required().min(2),
age: yup.number().required().positive().integer(),
});
function App() {
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: yupResolver(schema),
});
const onSubmit = data => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} placeholder="First Name" />
{errors.firstName && <p>{errors.firstName.message}</p>}
<input {...register("age")} placeholder="Age" type="number" />
{errors.age && <p>{errors.age.message}</p>}
<button type="submit">Submit</button>
</form>
);
}
export default App;
React Hook Form의 watch 기능을 사용하면 폼 필드의 변화를 실시간으로 감지할 수 있음. watch는 특정 필드나 모든 필드의 현재 값을 확인할 수 있게 해줌.
const { register, watch } = useForm();
const watchFirstName = watch("firstName", "");
return (
<div>
<input {...register("firstName")} placeholder="First Name" />
<p>First Name: {watchFirstName}</p>
</div>
);
React Hook Form의 reset 기능을 사용하면 폼 데이터를 초기화할 수 있음. 이 기능은 폼을 제출한 후 데이터를 초기 상태로 되돌리거나, 특정 조건에 따라 폼을 초기화하고자 할 때 유용함.
const { register, handleSubmit, reset } = useForm();
const onSubmit = data => {
console.log(data);
reset(); // 폼 초기화
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} placeholder="First Name" />
<input {...register("lastName")} placeholder="Last Name" />
<button type="submit">Submit</button>
</form>
);
import React from 'react';
import { useForm } from 'react-hook-form';
function LoginForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => {
console.log("Login Data:", data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>Email:</label>
<input {...register("email", { required: "Email is required", pattern: /^\S+@\S+$/i })} />
{errors.email && <p>{errors.email.message