What are the main use cases of useRef?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Refs store mutable values that persist across renders without triggering re-renders: DOM element access, timer/subscription handles, and any 'instance variable' like previous values or latest-callback references.
Detailed explanation
useRef returns { current } — a box React preserves between renders but doesn't treat as state. Writing ref.current doesn't schedule a re-render, which is exactly what distinguishes it from useState. Classic uses: focusing/scrolling/measuring DOM nodes (ref={inputRef} then inputRef.current.focus()), holding interval or websocket handles so cleanup can reach them, tracking previous prop/state values for comparisons, storing whether a fetch is in-flight without re-rendering, and implementing latest-value refs so callbacks always see fresh data. Rules of thumb: if UI should update when the value changes, use state; if it's bookkeeping invisible to render output, a ref fits. Never read/write ref.current during render itself — do it in handlers or effects to keep renders pure.
Official docs:React docs: useRef
Example
function Stopwatch() {
const [ms, setMs] = useState(0);
const intervalRef = useRef<number>();
const startedAtRef = useRef<number>();
const start = () => {
startedAtRef.current = Date.now();
intervalRef.current = setInterval(
() => setMs(Date.now() - startedAtRef.current!), 50,
);
};
const stop = () => clearInterval(intervalRef.current);
return (<>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button> {Math.floor(ms / 1000)}s
</>);
}Interview tip
Lead with the key distinction — mutating a ref doesn't re-render — then give the stopwatch/timer example; it demonstrates persistence without state naturally.
Common mistakes
- Using useRef for values the UI depends on.
- Reading or writing ref.current during render.