UseRef[React]

SnowCat·2023년 1월 27일
0

React - Hooks

목록 보기
6/7
post-thumbnail

Reference?

  • JS에서는 getElementById, querySelector 등을 사용해서 직접적으로 DOM을 가져오고는 했음
  • 리액트에서 DOM을 직접 조작하고자 하는 경우 reference를 사용하게 됨

Example

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
  • input에 ref로 inputEl 객체를 전달해 버튼 클릭시마다 focus() 속성이 적용되도록 함
  • UseRef는 자손 요소에 특정한 속성을 주거나 변경해야 할 때, 값을 변경해야하지만 리렌더링을 방지해야 할 때 유용하게 사용할 수 있음

UseRef의 특징

  • Ref 내부의 값을 변경해도 컴포넌트가 다시 렌더링 되지 않음
  • 컴포넌트가 다시 렌더링 되더라도 ref 내부의 값은 바뀌지 않음

출처:
https://ko.reactjs.org/docs/hooks-reference.html#useref

profile
냐아아아아아아아아앙

0개의 댓글