React & Modern Frontend (445 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)
When do you need to use refs?
There are few use cases to go for refs,
- Managing focus, text selection, or media playback.
- Triggering imperative animations.
- Integrating with third-party DOM libraries.
Practical Code Example
jsx
// When to use refs:
// 1. Managing focus, text selection, or media playback
// 2. Triggering imperative animations
// 3. Measuring element dimensions (getBoundingClientRect)
function AutoFocusInput() {
const inputRef = useRef(null);
useEffect(() => { inputRef.current?.focus(); }, []);
return <input ref={inputRef} />;
}