1seul357

react-hook-form 본문

TIL

react-hook-form

1seul 2024. 8. 4. 13:57

React Hook Form

react-hook-form은 React 기반의 폼 관리 라이브러리로, 효율적인 폼 관리가 가능하다. state를 사용한 상태 관리를 할 필요가 없고, 간단하게 폼 유효성 검사도 할 수 있다.

설치

npm install react-hook-form

예시

import { useForm, SubmitHandler } from "react-hook-form"

type Inputs = {
  example: string
  exampleRequired: string
}

export default function App() {
  const { register, handleSubmit, watch, formState: { errors }} = useForm<Inputs>()
  const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input defaultValue="test" {...register("example")} />
      <input {...register("exampleRequired", { required: true })} />
      {errors.exampleRequired && <span>This field is required</span>}
      <input type="submit" />
    </form>
  )
}

register

입력 또는 선택 요소를 등록하고 유효성을 검사할 수 있다. 제공되는 옵션은 다음과 같다.

  • required : 필드에 값을 입력해야 한다.
  • maxLength : 값의 최대 길이
  • minLength : 값의 최소 길이
  • max : 최대값
  • min : 최소값
  • pattern : 입력에 대한 정규식 패턴이다.
  • validate : 콜백 함수를 통해 유효성 검사를 한다.

watch

register로 등록된 입력 값을 반환한다. watch(”example”) 은 example 필드의 값을 반환하게 된다. watch를 사용하면 필드 값을 확인할 수 있기 때문에 별도로 state와 같은 상태 관리를 할 필요가 없다. 제공되는 메서드 중에 getValues도 필드의 값을 반환한다. getValues는 watch와 다르게 값을 반환할 때, 리렌더링을 하지 않는다.

handleSubmit

폼을 제출하는 메서드이다. <form onSubmit={handleSubmit(onSubmit)}> 폼 제출 후의 진행되는 로직을 handleSubmit 매개변수로 넣으면 된다. form 태그에 쓰면 button에는 표시할 필요가 없다.

setValue

필드의 값을 동적으로 설정하고, 폼 상태를 업데이트할 수 있다. setValue(”example”, “test”) 는 example 필드의 값을 test로 바꾸게 된다. 버튼을 클릭했을 때, input 태그의 값을 강제로 바꿔야 하는 경우 사용하면 유용하다.

setFocus

setFocus(”example”) example로 등록된 입력 필드에 자동으로 포커싱이 된다.

setError

폼에 오류를 설정할 수 있다. setError를 통해 register로 등록된 필드에 오류를 설정하고, 해당 오류는 errors를 통해 가져올 수 있다.

import * as React from "react"
import { useForm } from "react-hook-form"

type FormInputs = {
  username: string
}

const App = () => {
  const { register, handleSubmit, setError, formState: { errors }} = useForm<FormInputs>()
  
  const onSubmit = (data: FormInputs) => {
	  if (data.username.length < 2) {
		  setError("username", { message : "이름은 최소 두글자 이상이어야 합니다." });
	  }
	}

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("username", { minLength: 2 })} />
      {errors.username && <p>{errors.username.message}</p>}
      <input type="submit" />
    </form>
  )
}

react-hook-form을 사용해야 하는 이유

  • 별도의 상태 관리를 하지 않아도 된다. form의 항목이 2-3개 정도이면 괜찮지만 만약 5개 이상이 되는 경우 그만큼의 상태 관리를 해줘야 하기 때문에 코드가 복잡해질 수 있다. 또한 useState로 관리한 경우는 값을 입력할 때 마다 페이지가 리렌더링 되지만 react-hook-form은 불필요한 리렌더링을 방지할 수 있다.
  • 효율적인 유효성 검사가 가능하다. 내장된 메서드들을 통해 값의 유효성 검사를 할 수 있고, 에러도 만들어 보여줄 수 있다.

'TIL' 카테고리의 다른 글

쿼리 스트링과 searchParams  (1) 2024.10.07
react-player  (0) 2024.08.18
FSD 아키텍처  (0) 2024.07.24
Storybook  (1) 2024.07.23
TypeScript  (0) 2022.07.27