useRef()

김민석·2021년 3월 31일
0

react

목록 보기
6/11

useRef() 공식 문서

useRef는 class형태의 react에서 사용되던 React.createRef()와 다른 기능이 하나 추가 되었기 때문에 이곳에 기록함.

useRef란?

const refContainer = useRef(initialValue);

초기값을 인자로 주는 것으로 새로운 객체를 만든다고 한다.
이 ref 객체의 형태는 다음과 같다.

{current: initialValue}

용법

용법에는 기존 React.createRef()와 동일하게 사용되던 용법 1)

그리고 새로 추가된 용법 2) 가 있다.


기존 용법

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>
    </>
  );
}

Dom 객체를 지정하는 용법이다.
ref라는 속성을 지정하고 거기에 useRef로 생성된 객체를 집어넣어서
current 안에 DOM 정보를 저장하는 것처럼 (확실하진 않으므로.) 보인다.

다른 용법

However, useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.

This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

위 인용문은 공식문서에서 가져온 것이다.

이 용법에 대해 설명해보자면,
useRef()는 javascript 객체를 생성하는데,

{current : something}  // <-- useRef로 생성된 객체의 모양

useRef로 생성된 객체는 갑쇼이 변화해도 re-render가 되지 않기 때문에

Component 안에서 수시로 값이 변하며, 해당 값으로 re-render를 일으키고 싶지 않은 값들을 저장해놓기
안성 맞춤이다.

0개의 댓글