useRef
는 두 가지 주요 용도로 사용돼:
TypeScript에서는 이 두 용도에 따라 타입을 다르게 지정해줘야 해.
import { useRef, useEffect } from 'react';
const InputFocus = () => {
const inputRef = useRef<HTMLInputElement>(null); // DOM 요소 참조
useEffect(() => {
inputRef.current?.focus(); // 페이지 로드시 자동 포커스
}, []);
return <input ref={inputRef} />;
};
✅ DOM 참조에는 <HTMLInputElement> 같이 해당 요소의 타입을 명시하고, 초기값은 null을 줘야 해.
const Timer = () => {
const countRef = useRef(0); // number 타입 자동 추론
const increase = () => {
countRef.current += 1;
console.log(`Ref count: ${countRef.current}`);
};
return <button onClick={increase}>Ref 증가</button>;
};
✅ useRef는 값을 변경해도 리렌더링되지 않아.
대신
.current
를 통해 값을 직접 조작할 수 있고, 상태 유지용으로도 유용해.
type Props = {
onRefReady: (el: HTMLDivElement | null) => void;
};
const MyBox = ({ onRefReady }: Props) => {
const divRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
onRefReady(divRef.current);
}, []);
return <div ref={divRef}>내용</div>;
};
✅ 초기엔 null이므로 타입도 HTMLDivElement | null로 명시해줘야 해.
컴포넌트 외부로 ref를 전달할 때 유용한 패턴이야.
const FocusButton = () => {
const inputRef = useRef<HTMLInputElement>(null);
const handleClick = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>포커스 주기</button>
</>
);
};