useRef solves two unrelated problems that happen to share one hook: reaching a real DOM element directly, and holding a value across renders that changing shouldn't trigger a re-render for.
Sometimes you need the actual DOM element — focusing an input, measuring an element's size, integrating a non-React library. Attaching a ref to a JSX element gives you exactly that:
function SearchBox() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current.focus(); // .current is the real <input> DOM node
}
return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>Focus the input</button>
</div>
);
}inputRef.current is null until React actually renders the <input>, then becomes the real DOM node — the same HTMLInputElement you'd get from document.querySelector in the JavaScript DOM lesson.
This is the part that trips people up coming from useState: changing ref.current does not cause a re-render. That's a feature, not a limitation — for something like tracking an interval ID or a previous value, you specifically don't want a re-render every time it changes:
function Stopwatch() {
const [running, setRunning] = useState(false);
const intervalRef = useRef(null);
function start() {
setRunning(true);
intervalRef.current = setInterval(() => {
console.log('tick');
}, 1000);
}
function stop() {
setRunning(false);
clearInterval(intervalRef.current); // reading it back later, no re-render involved either way
}
return <button onClick={running ? stop : start}>{running ? 'Stop' : 'Start'}</button>;
}| Changing it triggers a re-render? | Use for | |
|---|---|---|
| useState | Yes | Anything the UI should visibly reflect |
| useRef | No | DOM access, or a value the component needs to remember but never displays directly |
Don't read/write refs during render
Reading or writing ref.current during render (not inside an event handler or an effect) is a mistake to watch for — since it doesn't trigger a re-render, the UI can silently get out of sync with what the ref actually holds. Keep ref reads/writes inside handlers and effects.