Trivia Questions2 min readPremium

useRef in React

useRef(initialValue) returns an object { current: initialValue } that stays the same object for the life of the component. Changing ref.current does not trigger a re-render. That makes it the right tool for two jobs: holding a DOM node, and holding a value you need to remember but not display.

1. Accessing a DOM node

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

  useEffect(() => {
    inputRef.current.focus(); // set after React commits the DOM
  }, []);

  return <input ref={inputRef} type="search" />;
}

React sets inputRef.current to the element when it mounts and back to null when it unmounts. Use it for focus, scrolling, measuring, and integrating non-React libraries.

2. Holding a mutable value

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

  const start = () => {
    if (intervalRef.current !== null) return; // already running
    intervalRef.current = setInterval(() => setSeconds((s) => s + 1), 1000);
  };

  const stop = () => {
    clearInterval(intervalRef.current);
    intervalRef.current = null;
  };

  useEffect(() => stop, []); // clear on unmount

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

The interval ID isn’t shown on screen, so it doesn’t belong in state.

3. useRef vs useState

useRef useState
Changing it re-renders No Yes
Value available Immediately after assignment On the next render
Read during render Avoid Yes
Use for DOM nodes, timer IDs, previous values, flags Anything the UI displays

Rule of thumb: if the screen should change when the value changes, it’s state.

4. Don’t read or write refs during render

// Avoid: render output now depends on a value React can't track
return <p>{countRef.current}</p>;

Rendering should be pure. Read and write refs in event handlers and effects. The exception is one-time lazy initialisation:

const cacheRef = useRef(null);
if (cacheRef.current === null) cacheRef.current = new Map();

5. Two patterns worth knowing

Previous value

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value; // runs after render, so render sees the old value
  });
  return ref.current;
}

Latest callback (avoid re-subscribing when a handler changes)

function useInterval(callback, delay) {
  const saved = useRef(callback);
  useEffect(() => {
    saved.current = callback;
  });
  useEffect(() => {
    const id = setInterval(() => saved.current(), delay);
    return () => clearInterval(id);
  }, [delay]);
}

6. Ref callbacks

Pass a function instead of a ref object when you need to run code as a node attaches, for example to measure it or to keep a map of list items:

<li ref={(node) => { if (node) itemsRef.current.set(id, node); else itemsRef.current.delete(id); }} />

7. Refs to your own components

A ref on a DOM element just works. To let a parent reach a node inside your component, accept ref as a prop (React 19) or wrap the component in forwardRef (earlier versions).

Choosing: ref or state?

Need Use
Focus, scroll or measure an element useRef
Store a timer, observer or subscription useRef
Remember a value without re-rendering useRef
Show the value in the UI useState
Derive it from props or state Neither: compute it during render

Follow-up questions to expect

  • “Why didn’t my component update when I changed the ref?” By design. Refs are invisible to rendering.
  • “Why is ref.current null in my effect?” The element is rendered conditionally, or the ref is on a component that doesn’t forward it.
  • “When would you measure in useLayoutEffect instead?” When you need the measurement before paint to avoid flicker. See useEffect vs useLayoutEffect.