Skip to main content
InterviewHubPRO
Section Overview
Q202

Question 202 of 407

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

50%
React Core & Hooks (407 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)

When do you need to use refs?

mid LevelCode ExampleFormsPerformance

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} />;
}