Recent Posts
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
관리 메뉴

개발자 박가나

[250107 TIL] 본캠프 68일차 (React Hook Form과 Zod) 본문

내일배움캠프

[250107 TIL] 본캠프 68일차 (React Hook Form과 Zod)

gnchoco97 2025. 1. 7. 21:07

제어 컴포넌트

React에 의해 값이 제어되는 컴포넌트로서, 입력 값을 state로 관리하고 값이 변경될 때마다 리렌더링이 발생한다.

 

값에 대한 즉각적인 피드백이 필요한 경우 사용된다.

export default function Component() {
    const [inputValue, setInputValue] = useState(null);

    const handleChange = (e) => {
    	setInputValue(e.target.value);
    };

    return (
    	<input onChange={(e) => handleChange(e)} value={inputValue} />
    );
}

 

 

비제어 컴포넌트

React에서 값이 제어되지 않는 컴포넌트로서, 값이 변경되더라도 리렌더링이 발생하지 않는다.

 

값에 대한 즉각적인 피드백 대신 제출 시에만 값이 필요하거나 불필요한 렌더링을 방지하고 싶은 경우 사용된다.

export default function Component() {
    const inputNode = useRef(null);

    return (
    	<input ref={inputNode} />
    );
}

 

 

React Hook Form

React 애플리케이션에서 form을 효율적으로 관리하고 검증하기 위해서 사용되는 비제어 컴포넌트 기반의 라이브러리이다.

  • 빠른 성능 : 비제어 컴포넌트를 사용하여 리렌더링 최소화
  • 간편한 사용 : 최소한의 코드로 form 관리
  • 유연성 : 다양한 검증 라이브러리와 통합 가능
yarn add react-hook-form
'use client';
import { useForm } from 'react-hook-form';

export default function SignInForm() {
    const { register, handleSubmit, formState: { errors } } = useForm();

    const onSubmit = () => {};

    return (
        <form className="flex flex-col gap-4 p-5 items-center w-full m-auto" onSubmit={handleSubmit(onSubmit)}>
            <div className="flex flex-col gap-2">
            	<label htmlFor="email">Email</label>
                <input
                    className="text-black"
                    id="email"
                    type="text"
                    placeholder="Email"
                    {...register("email", {
                        required: "Email is required",
                        pattern: {
                            value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
                            message: "Invalid email address",
                        },
                    })}

                />
                {errors.email && <p className="text-red-500">{errors.email.message}</p>}
            </div>

            <div className="flex flex-col gap-2">
                <label htmlFor="password">Password</label>
                <input
                    className="text-black"
                    type="password"
                    placeholder="Password"
                    {...register("password", {
                    	required: "Password is required",
                    })}
                />
                {errors.password && <p className="text-red-500">{errors.password.message}</p>}
            </div>
            
            <button className="bg-gray-800 text-white px-4 py-2 rounded-md" type="submit">Sign In</button>
        </form>
    );
};

 

 

Zod

JavaScrit(TypeScript)를 위한 스키마 선언 및 검증 라이브러리이다.

  • 직관적인 API : 선언적인 방식으로 스키마 정의 가능
  • 타입 안전성 : TypeScript와의 강력한 통합 제공
  • 유연성 : 다양한 검증 규칙과 커스텀 메시지 지원
yarn add zod
import { z } from 'zod';

const userSchema = z.object({
    firstName: z.string().min(1, "First name is required"),
    lastName: z.string().min(1, "Last name is required"),
});

try {
	userSchema.parse({ firstName: "John", lastName: "" });
} catch (e) {
	console.error(e.errors);
}