참고자료 - useRef
참고자료 - DOM with Refs
참고자료 - 예제 한글자료
변수관리를 위해 사용되는 react hooks이다. Ref는 Reference의 약자이다.
보통 변수관리라 하면 useState가 일반적으로 떠오를 것이다.
이 둘에는 큰 차이가 있다.
useState는 변수가 변하면서 렌더링이 수행된다.
공통적으로 useRef가 reference하는 object는 current라는 property가 생긴다. 이 것은 참조하는 object에 따라서 어떠한 타입도 될 수 있다.
1. 변수관리
function App() {
const [render, setRender] = useState(false);
const countRef = useRef(0);
let countVar = 0;
console.log('***** 렌더링 후 Ref:', countRef.current);
console.log('***** 렌더링 후 Var:', countVar);
const increaseRef = () => {
countRef.current = countRef.current + 1;
console.log('Ref Up! --->', countRef.current);
}
const increaseVar = () => {
countVar = countVar + 1;
console.log('Var Up! --->', countVar);
}
const doRender = () => {
setRender(!render);
}
.
.
.
}
위와같은 예제에서 기본적인 변수는 렌더링시 0으로 초기화되지만, useRef로 정의된 변수는 렌더링되어도 초기화되지 않는다.
즉, 컴포넌트의 전 생애주기를 통해 유지된다.
2. DOM요소 접근
function App() {
const inputRef = useRef();
useEffect(() => {
console.log(inputRef);
inputRef.current.focus();
}, [])
const loginAlert = () => {
alert(`환영합니다. ${inputRef.current.value}`);
inputRef.current.focus();
}
return (
<div className="App">
<header className="App-header">
<input ref={inputRef} type="text" placeholder="id"/>
<button onClick={loginAlert}>Login</button>
</header>
</div>
);
}
위와 같은 예제같이 태그에 ref속성을 줘서 해당 태그(elment)를 주시하게 할 수 있다.