← Back to all snippets
JAVASCRIPT

Using `useRef` for Auto-Focusing an Input on Mount

Learn how to use the React `useRef` hook to directly interact with the DOM, enabling functionality like automatically focusing an input field when a component renders.

import { useEffect, useRef } from 'react';

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

  useEffect(() => {
    // Check if the ref has a current DOM node and then focus it
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []); // Empty dependency array ensures this effect runs only once on mount

  return (
    <div>
      <label htmlFor="autofocus-input">Your Name:</label>
      <input
        id="autofocus-input"
        type="text"
        ref={inputRef} // Attach the ref to the input element
        placeholder="Type here..."
      />
    </div>
  );
}
How it works: This snippet demonstrates a common use case for `useRef`: direct DOM manipulation. The `inputRef` is initialized with `null` and then attached to the `input` element via the `ref` prop. Inside a `useEffect` hook, which runs only once after the initial render (due to an empty dependency array), we check if `inputRef.current` exists (meaning the DOM element is available). If it does, we call `inputRef.current.focus()` to programmatically set focus on the input field, providing a better user experience for forms or search bars.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs