Skip to the content

Lesson 167 of 296

useRef

What you will learn

  • What a ref is
  • Accessing DOM elements
  • Storing values that should not cause re-renders
  • Refs vs state
  • Passing refs to your own components
On this page

What is a ref?

useRef gives you a small box that keeps a value between renders: an object { current: value }. Two important facts:

  • Changing ref.current does not cause a re-render.
  • The same box is returned on every render.

Use 1: accessing DOM elements

TSX
import { useRef } from "react";

function SearchWithFocus() {
  const inputRef = useRef<HTMLInputElement>(null);
  return (
    <>
      <input ref={inputRef} aria-label="Search" />
      <button type="button" onClick={() => inputRef.current?.focus()}>
        Focus search
      </button>
    </>
  );
}

React puts the DOM element into inputRef.current after the element is created, and sets it back to null when it is removed. Use DOM refs for: focusing, scrolling into view, measuring size, playing videos, and connecting non-React libraries (charts, maps).

Use 2: values that should not trigger a render

Timer IDs, previous values, flags, and anything you need to remember but not show:

TSX
function Stopwatch() {
  const [elapsedMs, setElapsedMs] = useState(0);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  function start() {
    if (intervalRef.current !== null) return;
    const startedAt = Date.now() - elapsedMs;
    intervalRef.current = setInterval(() => setElapsedMs(Date.now() - startedAt), 100);
  }

  function stop() {
    if (intervalRef.current !== null) clearInterval(intervalRef.current);
    intervalRef.current = null;
  }

  return (
    <div>
      <p>{(elapsedMs / 1000).toFixed(1)}s</p>
      <button type="button" onClick={start}>Start</button>
      <button type="button" onClick={stop}>Stop</button>
    </div>
  );
}

ReturnType<typeof setInterval> (Lesson 111) works in both browser and Node.js typings.

Refs vs state

useStateuseRef
Changing it re-rendersYesNo
Value available in render for displayYesShould not be read during render
UpdatesThrough the setter, applied on the next renderImmediately, by assignment
Use forAnything shown on screenDOM nodes, timer IDs, mutable bookkeeping

Rule: do not read or write ref.current during rendering (except to initialise it lazily). Read and write it in event handlers and effects. Otherwise the screen can get out of sync with the data.

Storing the previous value

TSX
function usePrevious<T>(value: T): T | undefined {
  const ref = useRef<T | undefined>(undefined);
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
}

The effect runs after render, so during render ref.current still holds the value from the previous render. (A common interview hook. Note it reads the ref during render on purpose; it is a well-known exception.)

Passing refs to your own components

In React 19, ref is a normal prop for function components:

TSX
import type { Ref } from "react";

function TextField({ label, ref }: { label: string; ref?: Ref<HTMLInputElement> }) {
  return (
    <label>
      {label}
      <input ref={ref} />
    </label>
  );
}

In React 18 and earlier, you had to wrap the component with forwardRef. You will see forwardRef in many existing codebases.

How to say it in an interview

"useRef returns a mutable object whose current value persists across renders without causing re-renders. I use it to reach DOM nodes for focus, scrolling or measuring, and to store things like interval IDs or the previous value. Anything displayed belongs in state instead, and I avoid reading refs during render. In React 19, ref is a regular prop, so forwardRef is no longer needed for new code."

Key words

WordMeaning
RefA box { current } that persists without re-rendering
DOM refA ref attached to an element with the ref attribute
forwardRefThe older way to pass refs into components

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.