React에서 폼을 관리하는 가장 기본적인 방법은 useState를 활용하는 것입니다. 하지만 이 방식은 다음과 같은 단점이 존재합니다.
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errors, setErrors] = useState({});
const handleSubmit = (e) => {
e.preventDefault();
let newErrors = {};
if (!email.includes("@")) newErrors.email = "유효한 이메일을 입력하세요";
if (password.length < 6) newErrors.password = "비밀번호는 6자 이상이어야 합니다";
setErrors(newErrors);
};
이러한 문제를 해결하기 위해 react-hook-form을 사용합니다.
react-hook-form은 비제어 컴포넌트(Uncontrolled Components) 기반으로 동작하는 라이브러리로, useState 없이 ref를 활용해 폼 상태를 관리합니다.
비제어 컴포넌트 기반이라 성능이 좋다.
react-hook-form 기본 사용법
import { useForm } from "react-hook-form";
const MyForm = () => {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("email", { required: "이메일을 입력하세요" })} />
{errors.email && <p>{errors.email.message}</p>}
<button type="submit">제출</button>
</form>
);
};
하지만, react-hook-form에도 한계가 있습니다.
이를 해결하기 위해 zod를 도입합니다.
zod는 TypeScript와 궁합이 좋은 스키마 기반 유효성 검사 라이브러리로, react-hook-form과 결합하여 유효성 검사 로직을 깔끔하게 정리할 수 있습니다.
zod를 사용한 폼 유효성 검사
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
// Zod 스키마 정의
const schema = z.object({
email: z.string().email("유효한 이메일을 입력하세요"),
password: z.string().min(6, "비밀번호는 6자 이상이어야 합니다"),
});
const MyForm = () => {
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: zodResolver(schema), // Zod와 연결
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("email")} />
{errors.email && <p>{errors.email.message}</p>}
<input {...register("password")} type="password" />
{errors.password && <p>{errors.password.message}</p>}
<button type="submit">제출</button>
</form>
);
};
왜 zod를 사용할까?
렌더링 성능 저하와 유효성 검사 코드 증가 문제를 초래한다.비제어 컴포넌트 기반으로 렌더링 성능을 최적화할 수 있다.유효성 검사 코드가 길어지는 단점이 존재한다.스키마 기반 검증으로 코드를 간결하게 유지할 수 있다.결과적으로 react-hook-form + zod 조합을 사용하면 렌더링 성능을 유지하면서도 유효성 검증을 효율적으로 수행할 수 있다.
[React] 제어 컴포넌트(Controlled Component)와 비제어 컴포넌트(Uncontrolled Component)
React-hook-form 사용 이유와 정리