React/know

useRef 알아보기

타코따코 2024. 11. 17. 15:06

useRef

input과 잘 어울림. 포커스 사용 가능

다른 hook과 달리 ‘랜더링’을 야기시키지 않음. 값만 저장 & 공유 가능.

 

 

DOM에 관여 하는 경우

const inputRef = useRef(null);

<input type="text" ref={inputRef} />

inputRef.current.value
inputRef.current.focus();

 

위 연결을 하면,

내가 원하는 inputText에 focus를 하거나, 값을 데이터로 가져올 수 있다. 

 

 

컴포넌트에 arg로 ref를 전달하는 경우 : forwardRef를 사용해야 에러가 안난다.  (리팩토링 사용시 필요)

const MyInput = forwardRef((props, ref) => {
  return <input {...props} ref={ref} />;
});

 

UI 랜더링 완료 후 ref로 DOM 연결이 필요해야함.

useEffect(() => {
    if (isPlaying) {
      ref.current.play();
    } else {
      ref.current.pause();
    }
  }, [isPlaying]);