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 it has rendered and attached it to the page, so you must use the remote after render. That means inside an effect or an event handler, never in the render body.
Reading inputRef.current while rendering gives null on the first render, and calling .focus() on null throws an error.
The plain HTML attribute autoFocus also works for simple cases like a search box. A ref gives more control: you can focus a different field after a validation error, or focus the input when a button is clicked rather than only on load.
Example
function Search() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} placeholder="Search trains" />;
}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.