--- id: react-refs-patterns title: React Refs 사용 패턴 category: Coding status: draft source_trust_level: B verification_status: conceptual created_at: 2026-05-09 updated_at: 2026-05-09 tags: [react, refs, dom, vibe-coding] tech_stack: { language: "TypeScript / React 18+", applicable_to: ["Web", "React Native"] } applied_in: [] aliases: [useRef, forwardRef, callback ref] --- # React Refs 사용 패턴 > ref 는 두 가지: (1) DOM 참조 — 측정/포커스/스크롤, (2) **렌더에 영향 안 주는 mutable 값** 보관. ref.current 변경은 재렌더 trigger 안 함. ## 📖 핵심 개념 - DOM 또는 자식 imperative API 노출 (focus, play, scrollTo 등). - 렌더 사이 보존하는 값 — previous value, timer id, mutable 카운터. - ref 변경은 재렌더 안 함 (state 가 아님). ## 💻 코드 패턴 ### DOM 측정 ```tsx function AutoFocus() { const inputRef = useRef(null); useEffect(() => { inputRef.current?.focus(); }, []); return ; } ``` ### Previous value ```tsx function usePrevious(value: T): T | undefined { const ref = useRef(); useEffect(() => { ref.current = value; }, [value]); return ref.current; } ``` ### Imperative handle 노출 ```tsx type VideoHandle = { play: () => void; pause: () => void }; const Video = forwardRef((props, ref) => { const videoRef = useRef(null); useImperativeHandle(ref, () => ({ play: () => videoRef.current?.play(), pause: () => videoRef.current?.pause(), }), []); return