Interview Q&A / System Design

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

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

#useref#dom

Related questions

Practise more System Design questions

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

Open System Design 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.