DOM에 접근하기 위해 고안된 hook이다.
사실 useRef로 선언된 변수는 DOM 뿐만이 아니라 어떤 값이든 저장할 수 있는 일반적인 자바스크립트 객체에 불과하다.
heap 영역에 저장되기때문에, 애플리케이션이 종료되거나 가비지 컬렉팅이 되기전까지 접근이가능하다.
react는 데이터 바인딩 및 갱신을 알아서 해주기에, DOM에 직접접근하는건 지양해야 하나, focus와 같이 부득이하게 DOM에 접근해야 할 경우 사용할 수 있는 hook이다.
state값 변경에 의해 컴포넌트가 re-rendering이 되더라도, DOM은 이미 존재하는채로 내부 데이터가 변경되기 때문에 useRef로 선언된 변수는 재정의 되지 않는다.
렌더링에 영향을 받지않는 상수변수를 사용하고싶을때도 활용가능하다.
이 경우, 선언만 해놓고 DOM을 할당시키지않으면 된다.
const cComp = () => {
const mounted = useRef(false);
const [a, setA] = useState(1);
const [b, setB] = useState(2);
useEffect(() => {
mounted = true;
console.log("gg");
}, []);
useEffect(() => {
if (mounted.current) {
console.log("a is changed");
}
}, [a]);
useEffect(() => {
if (mounted.current) {
console.log("b is changed");
}
}, [b]);
};
class cComp extends React.component {
input = null;
onClick = () => {
input.focus();
}
render() {
<>
<button onClick={this.onClick}>focus</button>
<input ref={(ref) => { this.input = ref }}/>
</>
}
}
current
property로 접근해야함을 주의하자.
import React, { useRef } from 'react';
const fComp = () => {
const inputRef = useRef(null);
const onClick = () => {
input.current.focus();
}
return (
<>
<button onClick={onClick}>focus</button>
<input ref={inputRef}/>
</>
)
}