CPCODELAB
React

useRef — DOM Access and Mutable Values

9 min read

Refs: Escape Hatch from the React Model

useRef returns a mutable object with a .current property that does not trigger a re-render when changed. It has two main uses: holding a reference to a DOM element, and storing a mutable value that persists across renders.

DOM access

jsx
import { useRef, useEffect } from 'react';

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

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return <input ref={inputRef} placeholder="I focus automatically" />;
}

Storing mutable values

jsx
function Timer() {
  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>
  );
}

Only reach for useRef when you need to escape React's rendering model. For values that should trigger UI updates when they change, use useState instead.

Ready to test yourself?
Practice React— quiz & coding exercises