Hint
Mutable box (.current) that persists across renders without causing re-renders — DOM access and storing mutable values
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 ;
}
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: