What is useRef and when should you use it?
· Category: React
Short answer
useRef returns a mutable object whose .current property persists across renders. It is commonly used to reference DOM elements or store previous values without causing re-renders.
How it works
Unlike state, updating a ref does not trigger a component re-render. When passed to a JSX ref attribute, React populates .current with the corresponding DOM node.
Example
import { useRef, useEffect } from 'react';
function TextInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} type="text" />;
}
When to use it
- Accessing or measuring DOM elements (focus, scroll, animations).
- Storing intervals, timeouts, or previous prop values.
- Holding mutable values that should not trigger renders, like a counter in an animation loop.
Tips
- Do not read or write
ref.currentduring render; do it in effects or event handlers. - Refs are not reactive; changes will not be reflected in JSX until the next render for other reasons.