useRef 훅 기초 정리useRef는 React의 Hook 중 하나로,ref는 reference(참조)의 약자import { useRef } from "react";
const myRef = useRef(초기값); // 초기값은 보통 null 또는 원하는 값
myRef.current로 실제 값 또는 DOM 객체에 접근import { useRef } from "react";
export default function Example1() {
const inputRef = useRef(null);
const handleClick = () => {
// input DOM에 직접 접근하여 포커스 이동
inputRef.current.focus();
// input의 현재 값 출력
console.log(inputRef.current.value);
};
return (
<>
<input ref={inputRef} />
<button type="button" onClick={handleClick}>등록</button>
</>
);
}
💡 input의 값을 단순히 읽거나 포커스를 줄 때 useRef가 유용합니다.
import { useEffect, useRef, useState } from "react";
export default function Example2() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
useEffect(() => {
// count가 변경될 때마다 countRef.current에 저장
countRef.current = count;
}, [count]);
return (
<>
<p>현재 count: {count} / 이전 count: {countRef.current}</p>
<button onClick={() => setCount(count + 1)}>증가</button>
</>
);
}
💡 useRef는 렌더링과 상관없이 값을 기억하므로, 이전 값을 추적할 때도 활용
import { useRef } from "react";
export default function Example3() {
const formRef = useRef();
const handleSubmit = () => {
// form DOM 전체에 접근
console.log(formRef.current);
// name 속성으로 input 값 추출
console.log(formRef.current.elements['textInput'].value);
// class로 input 값 추출
console.log(formRef.current.querySelector('.textInput').value);
};
return (
<>
<form ref={formRef}>
<input type="text" className="textInput" name="textInput" />
<select name="selectData">
<option>바나나</option>
</select>
<textarea name="text2Data"></textarea>
<button type="button" onClick={handleSubmit}>폼 전송</button>
</form>
</>
);
}
💡 form 전체를 참조하거나, 여러 input 값을 한 번에 다룰 때도 useRef가 편리합니다.
| 구분 | useState | useRef |
|---|---|---|
| 값 변경 시 | 컴포넌트 리렌더링 발생 | 리렌더링 발생하지 않음 |
| 용도 | 상태 관리, 화면 갱신 | DOM 참조, 값 임시 저장 등 |
useRef는 렌더링에 영향을 주지 않는 값을 저장할 때 사용useState 사용 권장