InterviewHubPRO
Section Overview
Q202

Question 202 of 445

Part 8: Advanced React Patterns, Portals & Performance (152 - 261)

45%
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,

  1. Managing focus, text selection, or media playback.
  2. Triggering imperative animations.
  3. 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} />;
}