State & Core HooksExtra· 30 min read

useRef

Reach into the DOM directly, or remember a value across renders without re-rendering.

What you will learn

  • Reference a DOM element with useRef
  • Focus an input programmatically
  • Know when to use ref vs state

A direct handle to an element

useRef gives you a reference to a real DOM element so you can do things like focus an input or measure it.

useRef focuses a DOM element
function App() {
  const inputRef = useRef(null);
  return (
    <div>
      <input ref={inputRef} placeholder="Click the button to focus me" />
      <button onClick={() => inputRef.current.focus()}>Focus the input</button>
    </div>
  );
}
Live preview

Step by step: useRef(null) creates an empty box called inputRef. We attach it to the input with ref={inputRef}, so React fills inputRef.current with the real input element. When the button is clicked, inputRef.current.focus() reaches into that real element and focuses it — the cursor jumps into the box. This is how you do direct DOM actions (focus, scroll, measure) that state cannot do.

Note: Output: An input and a Focus the input button. Click the button and the text box gains focus (the cursor appears inside it), ready for typing.

Note: Unlike state, changing a ref does not trigger a re-render. Use state for data shown in the UI; use ref for direct DOM access or values you want to remember without re-rendering.

Q. A key difference between useRef and useState is:

Answer: Updating a ref does not re-render the component, unlike state. Refs are for DOM access or persisting values silently.

✍️ Practice

  1. Use useRef to focus an input when a button is clicked.
  2. Use useRef to read the current value of an uncontrolled input.

🏠 Homework

  1. Build a search box that auto-focuses when the page loads (ref + useEffect).
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →