React Hooks - useRef

kiyeol·2023년 2월 15일
0
post-thumbnail

React 16.8 버전에서 새로 추가된 React Hooks 기능중
useRef에 대해 알아보도록 하자.

언제 사용할까?

- 렌더링에 필요하지 않은 값을 참조할 때
- DOM을 조작할 때
- 참조 콘텐츠 재생성 방지 할 때

어떻게 사용할까?

 function useRef<T>(initialValue: T|null): RefObject<T>;
  interface RefObject<T> {
        readonly current: T | null;
    }

useRef를 자세히 보면 모든 유형의 값 또는 null 넣을 수 있고, RefObject를 반환해주는걸 볼 수 있다.

RefObject은 current 속성을 가지고 있는 객체를 반환한다.

import { useRef } from 'react';

function Component() {
  const intervalRef = useRef(0);
  const inputRef = useRef(null);
  
  const onCreateCounter = () => {
    	intervalRef.current += 1;
	};
    
  const onReadCounter = () => {
  		const intervalId = intervalRef.current;
  		...
	};

}

참조 내부의 값을 업데이트하려면 current 속성에 접근해서 수동으로 값을 변경 할 수 있고, 다시 호출해서 읽을 수 있다.

주의

  • useRef는 참조를 변경해도 다시 렌더링되지 않습니다
  • 초기화를 제외하고는 렌더링 중에 쓰거나 읽지 ❌

useRef는 참조를 변경해도 다시 렌더링되지 않으므로 참조는 화면에 표시하려는 정보를 저장하는 데 적합하지 않고, 시각적 출력에 영향을 주지 않는 정보를 저장하는 데 적합하다.

예시)

useRef로 값을 참조

function MyComponent() {  ... ❌
  ...
  
  // Don't write a ref during rendering
  myRef.current = 123;

  //  Don't read a ref during rendering
  return <h1>{myOtherRef.current}</h1>;
}

function MyComponent() { ... ✅ 
   ...
  const [_, doSomething] = useState(null);
  
  useEffect(() => {
    myRef.current = 123;
  });

  function handleClick() {
    doSomething(myOtherRef.current);
  }
}

또한 useRef는 props로 바로 넘길 수 없다.

const inputRef = useRef(null);

return <Input ref={inputRef} />;
Warning: Function components cannot be given refs. 
Attempts to access this ref will fail. 
Did you mean to use React.forwardRef()?

다음과 같이 forwardRef() 요소를 사용해 ref를 props에 넘길 수 있다.

import { forwardRef } from 'react';

const Input = forwardRef(function MyInput(props, ref) {
  // ...
});

useRef로 DOM 조작

	//...
  const inputRef = useRef(null);
      // ...
    function handleClick() {
    	inputRef.current.focus();
  	}
  

  return (
  	<>
    	
    	<button onClick={handleClick}>
      		Click me!
    	</button>
    </>
  );

참고문서)
https://ko.reactjs.org/docs/hooks-reference.html#useref
https://beta.reactjs.org/reference/react/useRef

profile
kyday63@gamil.com

0개의 댓글