Interview Q&A / React

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you focus an input automatically when a component mounts?

SHORT ANSWER

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

jsx
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.

#useref#dom

Related questions

Practise more React questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open React quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.