useRef creates a mutable reference that persists across renders without causing re-renders when changed. Use it for accessing DOM elements, storing mutable values that don't need to trigger updates, and keeping references to timers or previous values.
What useRef Does:
.current property.current doesn't trigger re-renderUse Cases:
useRef vs useState:
useRef vs createRef:
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
const selectAll = () => {
inputRef.current.select();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus</button>
<button onClick={selectAll}>Select All</button>
</div>
);
}
// Scrolling to element
function ScrollToTop() {
const topRef = useRef(null);
const scrollToTop = () => {
topRef.current.scrollIntoView({ behavior: 'smooth' });
};
return (
<div>
<div ref={topRef} />
{/* ... lots of content ... */}
<button onClick={scrollToTop}>Back to Top</button>
</div>
);
}