에어비앤비 프로젝트에서 로그인에서의 이메일 유효성 검사와 같이 폼 하나만 사용하는 거라면 직접 구현하는 것이 성능에 더 좋겠지만 마켓컬리 회원가입 창이라던지 폼의 개수가 늘어나고 조건이 늘어갈수록 코드는 계속 길어졌다.
그래서 이번엔 유효성 검사를 도와주는 라이브러리를 사용해보려고 한다.
라이브러리를 사용하면 번들의 크기가 커져 프로젝트를 무겁게 할 수 있으니 라이브러리를 사용하기 전에 직접 구현이 나은지 라이브러리가 나은지 꼭 생각하고 구현하자.
라이브러리 사용을 정당화할만큼 코드가 복잡하고 양이 많은지 꼭꼭 고려하라는 말씀
formik 와 react-hook-form 비교한 좋은 글을 읽어보았다.
Client 단에서의 validation check 를 도와주는 라이브러리로 가장 많이 사용하는 두개를 비교한 글인데
formik+yup 이 더 많이 사용되나 디펜던시와 리렌더 횟수 등을 고려했을 때 react-hook-form 이 더 좋은 성능을 가지고 있다는 것 같다.
react-hook-form 으로 결정 땅땅 🕵🏻♀️
https://velog.io/@kihyun/React-Hook-Form-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0
npm install react-hook-form (or yarn add react-hook-form)
import { useForm } from "react-hook-form";
const { register, watch } = useForm({ mode: "onChange" });
<form onChange=handleSubmit(onSubmit, onError)로 바꿔주기>
</form>
useForm({mode:'onChange'})로 변할 때마다
Register 은 input 에서 값을 불러오기 위한 함수로 다른 옵션을 이용하면 input의 유효성 검사도 쉽게 할 수 있다.
import { useForm } from "react-hook-form";
const Auth=()=>{
const {register}=useForm();
return{
<form>
<input type="text" {...register("사용할 이름")} />
<input type="submit" />
</form>
</div>
}
}
위와 같이 사용해주면 register 안에 "사용할 이름" 을 가지고 input 값을 불러올 수 있다.
input 에서 불러오는 값을 실시간으로 확인할 수 있게 함.
import { useForm } from "react-hook-form";
const Auth=()=>{
const {register, watch}=useForm();
console.log(watch());
return{
<form>
<input type="text" {...register("사용할 이름")} />
<input type="submit" />
</form>
</div>
}
}
import { useForm } from "react-hook-form";
const Auth=()=>{
const {register, watch, handleSubmit}=useForm();
console.log(watch());
return{
<div>
<form onClick={handleSubmit(onSubmit, onError)}>
<input type="text" {...register("사용할 이름")} />
<input type="submit" />
</form>
</div>
}
}
여기까지 말그대로 바로 사용하기 위해 알아야할 기본적인 메소드들을 초간단하게 정리해봤다.
react-hook-form 공식문서를 보면서 공부해보자. 영어..지만
const {register, ... } = useForm({이 안에 들어가는 것들})
useForm({
mode: 'onSubmit',
reValidateMode: 'onChange',
defaultValues: {},
resolver: undefined,
context: undefined,
criteriaMode: "firstError",
shouldFocusError: true,
shouldUnregister: false,
shouldUseNativeValidation: false,
delayError: undefined
})
위의 코드는 useForm 의 모든 인자이다.
일단 내가 사용한 부분만 정리하려고 한다.
const {register, ... } = useForm({
mode:"onSubmit",
})
사용자가 폼을 제출하기 전에 유효성 검사를 어떻게 할지 결정하는 부분