What are the common use cases for useRef?
1. Accessing DOM elements: Directly interact with a DOM element.
import { useRef } from "react";
function DomAccessExample() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus(); // Programmatically focuses the input
};
return (
<div>
<input ref={inputRef} type="text" placeholder="Type here" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
2. Persisting mutable values: Keep mutable values that do not trigger re-renders (e.g., timers, counters).
import { useRef, useEffect } from "react";
function PageVisitTracker() {
const timeSpentRef = useRef(0);
const intervalRef = useRef(null);
useEffect(() => {
intervalRef.current = setInterval(() => {
timeSpentRef.current += 1;
}, 1000);
return () => {
clearInterval(intervalRef.current);
console.log(`User spent ${timeSpentRef.current} seconds on this page.`);
};
}, []);
return (
<div>
<h1>Welcome to the Page</h1>
<p>
Stay here for a while. The time spent will be logged when you leave or
refresh.
</p>
</div>
);
}
export default PageVisitTracker;
3. Storing previous state values: Capture the previous value of a state.
As below example, the prevCount.current is actually up to date with "count". But because when it is updated to current value of "count", it does not trigger the rerender => old value "count" still showing.
When the component is rerendered by anything after that, prevCount.current will show the latest value of "count".
import { useState, useRef, useEffect } from "react";
function PreviousStateExample() {
const [count, setCount] = useState(0);
const prevCount = useRef(null);
useEffect(() => {
prevCount.current = count; // Store the current count in ref
}, [count]);
return (
<div>
<p>Current Count: {count}</p>
<p>Previous Count: {prevCount.current}</p>
<button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
</div>
);
}