Agentic hosting is here. Connect to our MCP now ->

Blog

Understanding the useRef Hook in React

Changing a ref doesn't re-render your component, which is exactly what makes refs useful and what trips people up.

ยทby Steve Bonisteel

In React, Hooks are special functions that let you use state and other React features in function components. Among them, the useRef Hook is a valuable tool for two jobs: keeping values between renders without re-rendering, and accessing Document Object Model (DOM) elements directly.

The useRef Hook is simple, but developers often misunderstand it. Changing a ref doesn't re-render your component, which is exactly what makes refs useful and what trips people up.

In this article, you'll learn what useRef does, how to use it to work with the DOM and to keep values between renders, how it differs from useState, and what changed in React 19. The examples are tested with React 19.

What is the useRef Hook?

The useRef Hook gives your component a ref: an object with a single current property that you can read and change. It has two main uses: storing values that don't need to trigger a re-render when they change, and storing references to DOM elements.

To understand why refs are useful, it helps to know what happens when a component re-renders. React calls your component function again, so every regular variable declared inside it starts over from its initial value. State, on the other hand, persists: React keeps it between renders and gives you the latest value each time. Refs persist too, but unlike state, changing a ref doesn't cause a re-render.

Here's a component that shows all three side by side:

import { useRef, useState } from 'react';
 
function Demo() {
  let counter = 0;
  const [state, setState] = useState(0);
  const ref = useRef(0);
 
  counter++;
  ref.current++;
 
  return (
    <button onClick={() => setState(state + 1)}>
      {counter} / {state} / {ref.current}
    </button>
  );
}

After you click the button twice, it shows 1 / 2 / 3. The regular variable counter is reset on every render, so it's always 1. The state was updated twice, so it's 2. And the ref kept its value across all three renders, so it's 3. This example changes ref.current during rendering only to show how refs persist. In real code, avoid that, as you'll see in the rules below.

Implementing useRef in React

To use the useRef Hook, import it from React:

import { useRef } from 'react';

Then call it at the top level of your component with an initial value:

const myRef = useRef(null);

The Hook returns an object, { current: null }. React gives you the same object on every render, so anything you store in myRef.current is still there the next time the component renders.

Always pass an initial value. Use null for refs that will hold a DOM element, and the starting value, such as 0, for refs that store data. In TypeScript, calling useRef() without an argument is an error with React 19's types, so for a DOM element you'd write useRef<HTMLDivElement>(null).

To point a ref at a DOM element, pass it to the element's ref prop:

<div ref={myRef}>This is an example element</div>

After React renders the element, myRef.current holds the div DOM node, and you can use it in event handlers and effects:

useEffect(() => {
  console.log(myRef.current); // <div>This is an example element</div>
}, []);

Note that the ref is still null while the component renders for the first time, because React hasn't created the DOM element yet. That's why you access DOM refs in event handlers and effects, not directly in the component body.

DOM manipulation with the useRef Hook

Sometimes you need to work with a DOM element directly, for example, to move focus to an input, scroll to an element, measure its size, or hand it to a library that isn't built for React.

In plain JavaScript, you'd select the element with a method like getElementById or querySelector. Here's an example that focuses an input when a button is clicked. First, the HTML:

<div>
  <input type="text" id="myInput" />
  <button id="focusButton">Focus Input</button>
</div>

Then the JavaScript:

const input = document.getElementById('myInput');
const focusButton = document.getElementById('focusButton');
 
focusButton.addEventListener('click', () => {
  input.focus();
});

In React, you don't usually query the DOM like this. React creates and updates the DOM for you, so selecting elements by ID is fragile and works against React. Instead, you use a ref to get the element React created:

import { useRef } from 'react';
 
function FocusComponent() {
  const inputRef = useRef(null);
 
  const handleFocus = () => {
    inputRef.current.focus();
  };
 
  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleFocus}>Focus Input</button>
    </div>
  );
}

In this example, useRef creates inputRef, and the ref prop connects it to the input element. When you click the "Focus Input" button, handleFocus calls inputRef.current.focus() to focus the input.

Refs are best for actions that React doesn't handle for you, such as focusing, scrolling, playing media, and measuring. For things React does control, like an element's content, classes, or styles, use state instead. For example, to change a div's background color when you click a button, store the color in state rather than setting divRef.current.style.backgroundColor yourself:

import { useState } from 'react';
 
function ExampleComponent() {
  const [color, setColor] = useState('white');
 
  return (
    <div>
      <div style={{ backgroundColor: color }}>This is a sample div</div>
      <button onClick={() => setColor('red')}>Change Color</button>
    </div>
  );
}

If you change the DOM directly, React doesn't know about it, and the next render can undo your change or conflict with it.

Preserving values across re-renders

The second use of useRef is storing a value that has to survive re-renders but doesn't affect what's on the screen.

To understand the difference from state, compare two counters. Here's one with the useState Hook:

import { useState } from 'react';
 
function CounterComponent() {
  const [count, setCount] = useState(0);
 
  const increment = () => {
    setCount(count + 1);
  };
 
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

Each click updates the count state, which re-renders the component, so the page always shows the current count.

Page re-renders with the useState Hook
Page re-renders with the useState Hook

Here's the same counter with useRef:

import { useRef } from 'react';
 
function CounterComponent() {
  const countRef = useRef(0);
 
  const increment = () => {
    countRef.current = countRef.current + 1;
    console.log('Count:', countRef.current);
  };
 
  return (
    <div>
      <p>Count: {countRef.current}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

Each click updates countRef.current and logs the new value, but the component doesn't re-render. The console shows the count going up with every click, but the page still says Count: 0.

Page does not re-render with the useRef Hook
Page does not re-render with the useRef Hook

That's the key rule: if a value is shown on the screen, keep it in state. Use a ref for values that your event handlers and effects need, but your output doesn't.

A common example is a timer. To stop a timer, you need its ID, but the ID isn't something you display:

import { useRef, useState } from 'react';
 
function Stopwatch() {
  const [seconds, setSeconds] = useState(0);
  const intervalRef = useRef(null);
 
  const start = () => {
    if (intervalRef.current !== null) return;
    intervalRef.current = setInterval(() => {
      setSeconds((s) => s + 1);
    }, 1000);
  };
 
  const stop = () => {
    clearInterval(intervalRef.current);
    intervalRef.current = null;
  };
 
  return (
    <div>
      <p>{seconds} seconds</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
    </div>
  );
}

The seconds are displayed, so they live in state. The interval ID is only needed to stop the timer, so it lives in a ref, and storing it doesn't cause an extra render.

useRef vs useState

useRefuseState
ReturnsAn object, { current: value }A value and a function to update it
Changing it re-renders the componentNoYes
UpdateChange ref.current directlyCall the update function
Change is visibleImmediatelyIn the next render
Use forDOM elements, timer IDs, other values not shown on the screenAnything shown on the screen

Passing refs to your own components in React 19

Before React 19, a function component couldn't receive a ref prop directly. You had to wrap it in forwardRef. In React 19, ref works like any other prop:

import { useRef } from 'react';
 
function MyInput({ ref, ...props }) {
  return <input ref={ref} {...props} />;
}
 
function Form() {
  const inputRef = useRef(null);
 
  return (
    <div>
      <MyInput ref={inputRef} placeholder="Your name" />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </div>
  );
}

MyInput passes the ref it receives to the input element, so Form can focus the input inside it. forwardRef still works, but you don't need it for new code in React 19.

Rules and best practices for useRef

  • Don't read or write ref.current during rendering. React expects your component to return the same output for the same props and state. Read and change refs in event handlers and effects instead. The one exception is initializing a ref once, as in if (ref.current === null) ref.current = createSomething();.
  • Use state for anything shown on the screen. Changing a ref won't update the page, so a value that the user sees belongs in state.
  • Use refs for DOM access React doesn't handle. Focusing, scrolling, measuring, and integrating non-React libraries are good uses. Changing content or styles directly isn't.
  • Always pass an initial value. Use useRef(null) for DOM refs and useRef(0) or similar for values.
  • Don't overuse refs. If you find yourself syncing a ref with state or reading refs to decide what to render, you probably want state instead.

Summary

In this article, you explored the useRef Hook in React: what it is, how to use it to access DOM elements, and how to keep values between renders without re-rendering. You also learned how refs differ from state, how React 19 lets you pass a ref as a regular prop, and the rules that keep your components predictable.

The rule to remember is simple: use state for anything shown on the screen, and use a ref for DOM elements and values that only your event handlers and effects need.

When your React app is ready, you can deploy it for free with Sevalla's Static Site Hosting, or use Application Hosting if it needs a server.

Deep dive into the cloud!

Deploy your application, database, or static site in minutes.