Home About Skills Products
Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Tutorials · React JS

The useRef Hook - DOM Access and Mutable Values

The useRef Hook - DOM Access and Mutable Values

useRef returns a "box" whose .current property can hold any value — and unlike useState, changing that value does not trigger a re-render.

Use Case 1: Directly Accessing a DOM Element

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

  function focusInput() {
    inputRef.current.focus();
  }

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

Here inputRef.current is the actual DOM <input> element — this lets us call imperative DOM methods like .focus() or .scrollIntoView(), which isn't possible with state.

Use Case 2: Remembering a Value Without Re-rendering

function Stopwatch() {
  const [seconds, setSeconds] = useState(0);
  const intervalRef = useRef(null);

  function start() {
    intervalRef.current = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);
  }

  function stop() {
    clearInterval(intervalRef.current);
  }

  return (
    <div>
      <p>{seconds}s</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
    </div>
  );
}

If intervalRef were useState instead, setting the interval id would trigger an extra, unnecessary re-render every time. Refs are perfect for this kind of "backstage" value.

useState vs useRef

  • useState — use when the UI needs to update visibly when the value changes.
  • useRef — use when the UI does not need to update (a DOM node, a timer id, a previous value).

Key Takeaways

  • The ref attribute gives you direct access to a DOM node.
  • Updating .current does not trigger a re-render.
  • useRef is ideal for storing timer IDs, previous values, or DOM references.
What is React? JSX Introduction and Your First Component

What is React? JSX Introduction and Your First Component

What problem React actually solves, how JSX syntax works, and how to build your first component.

Setting Up a React App with Vite

Setting Up a React App with Vite

Set up a modern React project in seconds with Vite, and understand the resulting folder structure.

Understanding Components and Props

Understanding Components and Props

Build functional components and pass data from parent to child components using props.

Advertisement
Esc