useRef()이란?useRef를 사용하여 ref를 설정하면, useRef를 통해 만든 객체 안의 current값이 실제 Element를 가르키게 된다.useRef() 사용법import React, { useRef } from 'react';
const App = () => {
const inputEl = useRef(null);
const btnClick = () => {
let val = inputEl.current.value;
console.log('input value: ' + val);
}
return (
<input ref={inputEl} />
<button>확인</button>
);
}
export default App;
컴포넌트에서 로컬 변수를 사용해야 할 때도 useRef를 활용할 수 있다.
여기서 로컬 변수란 렌더링이랑은 관계 없이 바뀔 수 있는 값이다.
import React, { useRef } from 'react';
const App = () => {
const inputEl = useRef('Hello');
return (
<p>{inputEl.current}</p>
);
}
export default App;
ref 내부의 값이 변경되어도 컴포넌트가 렌더링이 되지 않는다.
그렇기 때문에 렌더링과 관련되지 않는 값을 관리 할 때만 사용한다.