Skip to content

QuizNot attempted

useRef for a DOM node (React 19 types)

In React 19 types, what is the type of inputRef, and why do you write inputRef.current?.focus()?
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => { inputRef.current?.focus(); }, []);
return <input ref={inputRef} />;
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • RefObject<HTMLInputElement | null>: current is null until React attaches the node (and after unmount)
  • Passing null to useRef<HTMLInputElement> picks the useRef<T>(initialValue: T | null): RefObject<T | null> overload, so current is honestly HTMLInputElement | null and must be narrowed
  • React 19 also made RefObject.current mutable and deprecated MutableRefObject.
  • Not RefObject<HTMLInputElement> with a readonly current: that was the React 18 typing for this call.
  • Not MutableRefObject<HTMLInputElement>: that is deprecated, and the node really is null before mount.
  • Not HTMLInputElement: useRef always returns a { current } box.