useRef는 두 가지 주요 용도로 사용돼:

  1. DOM 요소 참조
  2. 값 저장 (컴포넌트 리렌더링 없이 유지되는 값)

TypeScript에서는 이 두 용도에 따라 타입을 다르게 지정해줘야 해.


📘 예제 31: DOM 요소 참조 타입

import { useRef, useEffect } from 'react';

const InputFocus = () => {
  const inputRef = useRef<HTMLInputElement>(null); // DOM 요소 참조

  useEffect(() => {
    inputRef.current?.focus(); // 페이지 로드시 자동 포커스
  }, []);

  return <input ref={inputRef} />;
};

✅ DOM 참조에는 <HTMLInputElement> 같이 해당 요소의 타입을 명시하고, 초기값은 null을 줘야 해.


📘 예제 32: 값 저장용 useRef

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를 통해 값을 직접 조작할 수 있고, 상태 유지용으로도 유용해.


📘 예제 33: null 가능한 ref 타입

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를 전달할 때 유용한 패턴이야.


📘 예제 34: focus 처리 예제

const FocusButton = () => {
  const inputRef = useRef<HTMLInputElement>(null);

  const handleClick = () => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>포커스 주기</button>
    </>
  );
};