Course contentsShow
← React
Lesson 733 of 2,39619. useRefFree lesson

Auto-focusing Inputs on Mount

Use useEffect + ref.current.focus() to automatically focus an input when a component appears.

Auto-focusing Inputs on Mount

You'll learn how to automatically focus an input field the moment a component appears on screen.

Sometimes you want an input to be ready for typing immediately—think of a search modal that opens, or a login form where the username field should be active right away. React provides no built-in prop for this, but combining useRef with useEffect gives you complete control.

The Core Pattern

Here's the idea: you need to grab a reference to the DOM input element, then tell it to focus. But you can't focus it during render—the element doesn't exist yet! You need to wait until after the component mounts and the DOM is ready. That's where useEffect comes in.

import { useRef, useEffect } from 'react';

function SearchModal() {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
  }, []); // Empty array = run once on mount

  return <input ref={inputRef} type="text" />;
}

The empty dependency array ensures the focus happens exactly once: when the component first appears.

Why This Works

The ref gives you direct access to the actual <input> DOM node. After React finishes rendering and mounting the component, useEffect runs. At that moment, inputRef.current holds the real DOM element, and calling .focus() on it does exactly what you'd expect—moves the cursor there.

Common Scenarios

  • Modals and dialogs: Focus the first input when opened
  • Search bars: Focus on mount so users can type immediately
  • Multi-step forms: Focus the first field of each new step

Key Takeaway: Use useRef to reference the input, then call ref.current.focus() inside a useEffect with an empty dependency array to auto-focus when the component mounts.