How do you focus an input automatically when a component mounts?
Attach a ref to the input with ref={inputRef}, then call inputRef.current.focus() inside a useEffect with an empty dependency array. The ref is filled only after the element is in the DOM.
Explain it simply
The ref is a remote control for one specific DOM element. React fills ref.current with the element only after rendering it, so you must use the remote after render, which means inside an effect or an event handler.
Reading inputRef.current in the render body gives null on the first render.
Example
function Search() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} placeholder="Search trains" />;
}The HTML autoFocus attribute also works for simple cases, but a ref gives you control, for example focusing again after an error.
What to say in the interview
"I create a ref with useRef, pass it to the element's ref attribute, and call focus in an effect or event handler, because current is null until the DOM exists. For simple on-load focus autoFocus is enough, but a ref is better when focus depends on logic."
Common mistakes
- Calling inputRef.current.focus() during render, where current is null.