React · Frontend system thinking
How do you use refs to interact with DOM nodes?
Short answer
Attach a ref to a JSX element and read ref.current after commit. React sets it to the DOM node, so you can focus, measure, scroll or pass it to a third-party library.
A ref gives you an escape hatch to the underlying DOM node. During the first render the ref is null; React assigns the node after it creates and commits it. That is why DOM reads and writes belong in effects or event handlers, not in the render body.
function SearchForm() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return (
<form>
<label htmlFor="search">Search</label>
<input id="search" ref={inputRef} type="search" />
</form>
);
}Reasonable DOM ref uses
- Moving focus after navigation or opening a dialog
- Measuring an element before positioning a tooltip
- Scrolling an element into view
- Passing a node to a chart, map or video library
Prefer declarative React for anything React can render. Do not use a ref to set text, toggle classes or attach event listeners that JSX could handle. Direct DOM mutation bypasses React's model and can be overwritten on the next render.
function VideoPlayer({ src }) {
const videoRef = useRef(null);
function play() {
videoRef.current?.play();
}
return (
<div>
<video ref={videoRef} src={src} controls />
<button onClick={play}>Play</button>
</div>
);
}null again when that element unmounts. Always guard .current before using it.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is ref.current null on the first render?
- 2When should you use a callback ref instead of an object ref?
- 3How do you focus an input after a modal opens?
- 4Why is directly changing DOM text usually a bad idea in React?
Say it in the interview
I attach a ref to an element and read ref.current after React commits the DOM. That is useful for focus management, measurements, scrolling and integrating third-party widgets. I do not use refs for things JSX can express, because direct DOM changes bypass React and may be overwritten. I also guard current because it is null before mount and after unmount.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live React mock interview and get scored feedback on depth, clarity and confidence.