react-hook-form은 React에서 폼 상태와 검증을 효율적으로 관리하기 위한 라이브러리다.
Uncontrolled Component 기반 구조를 사용해 불필요한 렌더링을 줄이고, 코드 복잡도를 낮춘다.
기본 사용 구조
import { useForm } from "react-hook-form";
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
register: input 연결
handleSubmit: submit 처리
formState: 에러 및 상태 관리
가장 기본적인 예제
import { useForm } from "react-hook-form";
function LoginForm() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register("email", { required: "이메일 필수" })}
placeholder="email"
/>
{errors.email && <p>{errors.email.message}</p>}
<input
type="password"
{...register("password", { required: "비밀번호 필수" })}
placeholder="password"
/>
{errors.password && <p>{errors.password.message}</p>}
<button type="submit">로그인</button>
</form>
);
}
핵심 구조
input → register → react-hook-form → handleSubmit → data
register 옵션 정리 (validation)
register("email", {
required: "필수 입력",
minLength: { value: 6, message: "6자 이상" },
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: "이메일 형식 아님",
},
});
주요옵션
| 옵션 | 설명 |
| --------- | --------- |
| required | 필수 여부 |
| minLength | 최소 길이 |
| maxLength | 최대 길이 |
| min / max | 숫자 범위 |
| pattern | 정규식 |
| validate | 커스텀 검증 함수 |
커스텀 validate 사용법
<input
{...register("password", {
validate: (value) =>
value.length >= 8 || "8자 이상 입력",
})}
/>
formState 주요 속성
const {
formState: {
errors,
isDirty,
isValid,
isSubmitting,
touchedFields,
dirtyFields,
},
} = useForm();
defaultValues 사용법
const { register } = useForm({
defaultValues: {
email: "test@test.com",
password: "",
},
});
수정 페이지
서버 데이터 바인딩
초기값 세팅
Controller 사용법 (custom component)
custom select, datepicker, editor 같은 컴포넌트는
register로 직접 연결할 수 없다.
이때 Controller를 사용한다.
import { Controller, useForm } from "react-hook-form";
const { control } = useForm();
<Controller
name="country"
control={control}
render={({ field }) => (
<Select
{...field}
options={countries}
/>
)}
/>
언제 Controller를 쓰는가?
커스텀 드롭다운
DatePicker
React-Select
에디터(Editor.js, Quill, CKEditor)
watch — 실시간 값 추적
const { watch } = useForm();
const password = watch("password");
비밀번호 확인
조건부 렌더링
실시간 UI 반영
setValue / getValues
const { setValue, getValues } = useForm();
setValue("email", "test@test.com");
const values = getValues();
서버 데이터 수동 주입
자동완성
임시 저장 기능
reset — 폼 초기화
const { reset } = useForm();
reset();
reset({
email: "",
password: "",
});
초기화
서버 데이터 재바인딩