React의 Hook으로, 컴포넌트 생명주기 동안 변경 가능한 참조(reference)를 생성하는 함수
.current 프로퍼티를 통해 값에 접근하고 수정합니다.function RefExample() {
const countRef = useRef(0);
const handleClick = () => {
countRef.current += 1; // 리렌더링 발생 X
console.log(countRef.current);
};
}
Copyfunction PersistentRefExample() {
const lastRenderTime = useRef(Date.now());
// 컴포넌트가 다시 렌더링되어도 값 유지
console.log(lastRenderTime.current);
}
function InputFocusExample() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>포커스</button>
</>
);
}
function PreviousValueTracker() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
}, [count]);
const prevCount = prevCountRef.current;
}