Home / Learn React / useRef: Refs and the DOM

useRef: Refs and the DOM

A ref is a box that holds a value which survives renders but does not cause a re-render when it changes. It is also how you reach a real DOM element.

In shortconst ref = useRef(initial). Use ref.current to read or write. Attach to an element with ref={ref}.

Theory in plain words

State vs refuseStatechange triggers a rendershown on screenread while renderinguseRefchange does NOT renderinvisible bookkeepingread in handlers and effects
State vs ref

What it is

useRef returns a plain object { current: value } that React keeps for the whole life of the component.

Why we use it

Some things are not part of the screen data and should not trigger a render: a timer id, a previous value, a video element you need to play. Refs also let you call browser APIs such as focus() and scrollIntoView().

How it works

Changing ref.current does not tell React anything, so no render happens. When you put ref={myRef} on a JSX element React sets myRef.current to the DOM node after commit and to null when it is removed.

Where it is used

  • Focus an input, scroll to an element, play and pause media
  • Store timer and interval ids
  • Remember the previous value of a prop
  • Measure sizes and positions of elements

Focus an input

Focus with a refTry it Yourself

Keep a value without rendering

Stopwatch with an interval idTry it Yourself
Remember the previous valueTry it Yourself

The effect runs after the render, so during the render prev.current still has the older value.

Ref as a prop in React 19

Pass a ref to your own componentTry it Yourself

Since React 19 function components receive ref as a normal prop. Before, you needed forwardRef.

Ref callbacks

A callback ref (with cleanup in React 19)
<div ref={(node) => {
  // node is the DOM element
  const ro = new ResizeObserver(() => console.log(node.offsetWidth));
  ro.observe(node);
  return () => ro.disconnect();   // React 19: cleanup runs when the node goes away
}} />
Careful:Do not read or write ref.current during rendering (except for first time setup). It makes the component impure. Use it in handlers and effects. Avoid changing DOM that React manages, apart from simple things like focus and scroll.

Quick quiz

1. Does changing ref.current cause a re-render?

2. Which is a good use for a ref?

3. In React 19 how does a function component receive a ref?

Common questions

Does changing ref.current cause a re-render?

No. Refs are not reactive.

Which is a good use for a ref?

Storing a timer id. Values that should not trigger a render, like timer ids, fit refs.

In React 19 how does a function component receive a ref?

As a normal prop named ref. ref is a regular prop for function components since React 19.