Skip to content
UniCircle
MediumConceptualHooks

useRef

Question REACT-HKS-005

What is useRef used for? How is a ref different from state? Give two common uses.

Show the explanation

Model answer. useRef(initial) returns an object { current: initial } that keeps the same identity for the component's whole life. Changing ref.current does not cause a re-render.

Ref vs state:

  • State: changing it re-renders, and the value is a snapshot per render. Use it for anything shown on screen.
  • Ref: a mutable box that survives renders silently. Use it for values that do not affect what is drawn.

Common uses:

JSX
// 1. access a DOM node
function SearchBox() {
  const inputRef = useRef(null);
  useEffect(() => { inputRef.current.focus(); }, []);
  return <input ref={inputRef} />;
}

// 2. keep a mutable value between renders: a timer id
function Stopwatch() {
  const timer = useRef(null);
  const start = () => { timer.current = setInterval(tick, 1000); };
  const stop = () => clearInterval(timer.current);
}

Other uses: storing the previous value of a prop, or integrating non-React libraries (maps, charts) that need a DOM element. Avoid reading or writing ref.current during rendering (except for lazy initialisation), because it makes renders impure.

Original UniCircle question. Last reviewed 22 Oct 2026.