React Interview Question: What Is useRef Used For?
Short answer: useRef returns an object { current } that persists for the component's lifetime. Changing ref.current does not cause a re-render. It's used for DOM access and for mutable values that aren't part of what's displayed.
1. Accessing DOM elements
function SearchBox() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus search</button>
</>
);
}
2. Values that shouldn't trigger renders
function Stopwatch() {
const [elapsed, setElapsed] = useState(0);
const intervalRef = useRef(null); // the interval ID isn't shown on screen
const start = () => {
intervalRef.current = setInterval(() => setElapsed((e) => e + 1), 1000);
};
const stop = () => clearInterval(intervalRef.current);
return <>{elapsed}s <button onClick={start}>Start</button><button onClick={stop}>Stop</button></>;
}
Other examples: the previous value of a prop, a WebSocket instance, a flag like "has this request been aborted".
useRef vs useState
- useState: changing it re-renders; use it for anything the UI displays.
- useRef: changing it doesn't re-render; use it for "behind the scenes" values.
Mistakes to avoid
- Reading or writing
ref.currentduring rendering (except lazy initialisation); it makes components unpredictable. Use refs in event handlers and effects. - Storing displayed data in a ref and wondering why the screen doesn't update.
- Forgetting that
ref.currentisnulluntil the element mounts.
In React 19, function components can receive ref as a normal prop, so passing refs to your own components no longer needs forwardRef.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.