[모투] controlled, uncontrolled

Chanyoung Park·2024년 4월 11일
0

들어가며...

  • react-hook-form 라이브러리를 사용하던 도중 <Input/> 커스텀 컴포넌트에 register를 적용했는데, 작동이 되지 않았다.
  • 그 이유는 react-hook-form의 registerUncontrolled방식을 사용하는데, <Input/> 컴포넌트안에서 input에 focus를 주기위해 ref를 선언하였는데, ref가 덮어씌워지는 문제가 있었다.
type TInputProps = {
  label: Path<TSignUpProps>;
  register: UseFormRegister<TSignUpProps>;
} & React.InputHTMLAttributes<HTMLInputElement>;

const Input = (props: TInputProps) => {
  const inputRef = React.useRef<HTMLInputElement>(null);

  const onclick = () => {
    inputRef.current?.focus();
  };
  return (
    <div
      className="flex flex-col bg-primary-100 p-3 cursor-text
     "
      onClick={onclick}
    >
      <label className="cursor-text" htmlFor={props.label}>
        {props.label.toUpperCase()}
      </label>
      <input
        {...props.register(props.label)}
        ref={inputRef} // <- 이 부분이 문제가 됨
        placeholder={props.placeholder}
        className="bg-primary-100 outline-none"
      />
    </div>
  );
};

export default Input;

제어 컴포넌트(Controlled Component)

  • state로 관리가 되고 있는 컴포넌트로 state값이 변경될 때마다 갱신(재렌더링)이 되는 컴포넌트이다.

    "사용자의 입력을 기반으로 자신의 state를 관리하고 업데이트합니다."

비제어 컴포넌트(Uncontrolled Component)

  • state와는 무관한 컴포넌트이다.
  • react에서는 비제어 컴포넌트의 값을 알기 위해 ref를 통해 접근하는데, 이는 기존의 vanilla JS와 유사하다. (직접 DOM에 접근하는 방식)
  • 비제어 컴포넌트의 값을 알고 싶다면 ref.current.value를 통해 값을 가져올 수 있다.

결론

  • 기존의 ref로 react-hook-form의 register의 ref등록을 무효화시키는 문제를 겪으며, ref에 대한 이해를 하게 되었다.
  • ref로 값을 가져오는 경우에는 사용자의 입력을 받을때마다 재렌더링 되지 않고, 특정동작(버튼 클릭)시에만 값을 가져오므로 렌더링을 최적화할 수 있는 방법이 된다.

참고사이트

profile
더 나은 개발경험을 생각하는, 프론트엔드 개발자입니다.

0개의 댓글