const refObj = useRef(initialValue)'
getElementById
, querySelector
처럼 리엑트에서도 특정 DOM에 접근할 수 있다import React, { useRef, useState } from "react";
function App() {
console.log('rendering');
const [name, setName] = useState("");
const inputRef = useRef("");
const onFocus = () => {
setName(inputRef.current.value); // ref와 .current 프로퍼티를 통해 현재 input 창의 변경사항을 그대로 반영 가능
}
return (
<>
<input ref={inputRef} // ref={}를 통해 변경될 때마다 변경된 DOM 노드에 .current 프로퍼티 설정
// onChange={(e) => setName(e.target.value)}
/>
<button onClick={onFocus}>제출</button>
<div>input 한 내용은 {name}</div>
</>
)
}
export default App;
제출 버튼을 클릭했을 때만 렌더링이 일어나면 되기 때문에 input 값이 변할 때마다 onChange={(e) => setName(e.target.value)
를 부여하여 상태 값을 계속 바꾸기 보다는(리렌더링을 계속 하기 보다는) ref를 이용하여 리렌더링 없이 가변값을 유지하면 된다.
이를 이용하여 스크롤도 제어할 수 있다.