What is useRef and what are its two main use cases?
Hint
Mutable box (.current) that persists across renders without causing re-renders — DOM access and storing mutable values
Full Answer
useRef returns a mutable object { current: initialValue }. Changing .current does NOT trigger a re-render.
Use case 1: DOM access
function TextInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus(); // direct DOM access
}, []);
return <input ref={inputRef} />;
}
Use case 2: Storing mutable values (instance variables)
function Timer() {
const intervalRef = useRef(null);
const renderCount = useRef(0);
renderCount.current++; // doesn't trigger re-render
function start() {
intervalRef.current = setInterval(tick, 1000);
}
function stop() {
clearInterval(intervalRef.current); // access latest value, no stale closure
}
}
useRef vs useState for mutable values:
- Need re-render when it changes? → useState
- Just need to store/read without re-rendering? → useRef
💡 useRef solves the "stale closure" problem in event handlers or setInterval. Since .current is a stable object reference, you always read the latest value even from old closures.
More Hooks Questions
Practice this in a timed sprint
5 free questions, no signup required