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

Common DOM Operations: Focus

Using refs to programmatically focus input elements with the focus() method.

Common DOM Operations: Focus

You'll learn how to use refs to programmatically set focus on an input element, giving you full control over where user attention goes.

Why Focus Matters

Sometimes you need to control exactly where the user's cursor appears — like auto-focusing a search box when a modal opens, or moving focus to an error field after validation. You can't do this with state alone; you need direct access to the actual DOM element.

Using the focus() Method

Once you have a ref attached to an input (or other focusable element), you can call .focus() on ref.current to programmatically focus that element:

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

  function handleButtonClick() {
    // Direct DOM operation: focus the input
    inputRef.current.focus();
  }

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleButtonClick}>
        Focus the input
      </button>
    </div>
  );
}

When the button is clicked, inputRef.current points to the actual <input> DOM node, and calling .focus() on it immediately moves keyboard focus there — just like clicking into the field would.

Common Pattern: Auto-Focus on Mount

You'll often want to focus an element right after the component renders:

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

This is perfect for modals, dialogs, or forms where you want the user to start typing immediately.

Key Takeaway: With a ref attached to a DOM element, you can call ref.current.focus() to programmatically focus that element — giving you precise control over user interaction flow.