react-hook-form 사용하기

박찬미·2021년 12월 3일
0

https://react-hook-form.com/ 에 들어가준다.

제어컴포넌트는 state에 저장된 것을 사용한다. 안점함.

비제어컴포넌트는 state랑은 상관없고 input만 바뀐다.
실제 필요할 때 버튼을 클릭할 때 꺼내오는 것이다. 성능이 더 빠름

하지만 비제어컴포넌트가 더 좋은 것은 아니다. 장문으로 쓸 때 백프로 매칭이 안될 가능성이 있다. 예를들어 게시글이런 부분에 적당하다.
제어컴포넌트를 쓰면 state에 저장되어 정확성을 가지고 있다. 예를들어 결제부분 할 때 안정성이 필요할 때는 제어컴포넌트를 쓰는게 좋다.

사용할려면 터미널에 설치를 해준다.
yarn add react-hook-form 를 입력해 준다.

import { useForm } from "react-hook-form";

interface FormValues {
  myEmail: string;
  myPassword: string;
}

export default function ReactHookFormPage() {
  const { handleSubmit, register } = useForm();

  function onClickLogin(data: FormValues) {
    //loginUser API 요청하기!!!
    console.log(data);
  }

  return (
    <form onSubmit={handleSubmit(onClickLogin)}>
      이메일: <input type="text" {...register("myEmail")} />
      비밀번호: <input type="password" {...register("myPassword")} />
      <button>로그인하기</button>
    </form>
  );
}
 
profile
우당탕탕

0개의 댓글