useRef
hook은 DOM에 접근하기 위해 사용한다.
useRef
는 current
프로퍼티를 포함한 객체를 반환한다.
current
프로퍼티를 포함한 객체는 컴포넌트 전체 생명 주기에서 사용될 수 있고 리렌더링을 발생시키지 않으면서 데이터를 유지할 수 있도록 한다.
즉, useRef
값은 렌더링 중에도 같은 값을 유지할 수 있다.
문법
1
| const newRefComponent = useRef(initialValue);
|
- 주로 변형가능한 데이터를 리렌더링 없이 저장하기 위해 사용된다.
예시
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| function App() { const [anyInput, setAnyInput] = useState(" "); const showRender = useRef(0); const randomInput = useRef(null);
const toggleChange = (e) => { setAnyInput(e.target.value); showRender.current++; }; const focusRandomInput = () => { randomInput.current.focus(); };
return ( <div className="App"> <input className="TextBox" ref={randomInput} type="text" value={anyInput} onChange={toggleChange} /> <h3>Amount Of Renders: {showRender.current}</h3> <button onClick={focusRandomInput}>Click To Focus On Input </button> </div> ); }
export default App;
|
showRender
데이터는 toggleChange
이벤트가 발생할 때마다 값이 증가하고 해당 값이 화면에 렌더링된다. 이 때, 리렌더링 없이 showRender
값을 변형할 수 있다.
current
프로퍼티로 DOM에 접근하여 focus를 적용할 수 있다.