useRef
useRef lets a component remember a value between renders without causing a new render when that value changes.
import {useRef} from 'react';
function Example() {
const ref = useRef(0);
}
The returned object is conceptually:
{
current: 0
}
React keeps the same ref object for the mounted component instance.
The mental modelβ
ref.current is mutable.Changing ref.current does not ask React to render again. That makes refs useful for values React does not need to calculate JSX.
State versus refsβ
Retained between renders Β· setter schedules rendering Β· snapshot per render Β· use for UI-relevant data
Retained between renders Β· changing .current does not render Β· mutates immediately Β· use for non-render data
const [count, setCount] = useState(0);
const timeoutRef = useRef(null);
If the interface must display a value, state is usually the correct owner. If the value merely supports imperative/event/synchronization logic, a ref may fit.
A ref does not update the screenβ
function Counter() {
const countRef = useRef(0);
function handleClick() {
countRef.current += 1;
}
return (
<button onClick={handleClick}>
Count: {countRef.current}
</button>
);
}
The click mutates the ref, but it does not schedule a render. Use state when the rendered output depends on the value.
Good ref use casesβ
Refs are useful for values such as:
- timer IDs;
- DOM nodes;
- external library instances;
- previous/reference values used outside render;
AbortControllerinstances;- mutable caches that are not UI state;
- imperative handles.
Timer ID exampleβ
function DelayedMessage() {
const timeoutRef = useRef(null);
function schedule() {
timeoutRef.current = setTimeout(() => {
alert('Done');
}, 3000);
}
function cancel() {
clearTimeout(timeoutRef.current);
}
return (
<>
<button onClick={schedule}>Schedule</button>
<button onClick={cancel}>Cancel</button>
</>
);
}
The timeout ID matters to event logic, not JSX.
Refs are mutable immediatelyβ
const ref = useRef(0);
ref.current = 5;
console.log(ref.current); // 5
This differs from state: calling a state setter queues future React work while the current render keeps its existing state snapshot.
Do not read or write refs during renderβ
Bad:
function Component() {
const countRef = useRef(0);
countRef.current += 1; // β mutation during render
return <p>{countRef.current}</p>;
}
Rendering should remain pure. React may render repeatedly, interrupt work, or replay components in development checks.
Use refs from places where imperative mutation is expected:
- event handlers;
- Effects;
- ref callbacks;
- imperative APIs.
Exception: stable lazy initializationβ
A narrow deterministic pattern can be safe:
const playerRef = useRef(null);
if (playerRef.current === null) {
playerRef.current = new VideoPlayer();
}
Use this only when initialization is predictable and the result is stable for the component instance.
Ref identity is stableβ
Previous valuesβ
A common pattern stores the last committed value:
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
Use this only when the previous value is genuinely required. Many βprevious valueβ requirements indicate duplicated or awkward state modelling.
Refs and latest callbacksβ
Older code may keep the latest callback in a ref:
const callbackRef = useRef(onChange);
callbackRef.current = onChange;
That can still be useful for low-level integrations, but for non-reactive logic inside Effects in React 19.2+, first consider useEffectEvent because it communicates that intent directly.
Ref versus module variableβ
A module variable is shared by every component instance:
let timeoutId;
A ref belongs to one mounted component instance:
function SearchBox() {
const timeoutRef = useRef(null);
}
Ref versus local variableβ
A local variable is recreated each render. A ref survives renders.
Storing an external instanceβ
function MapView() {
const mapRef = useRef(null);
useEffect(() => {
mapRef.current = createMap();
return () => {
mapRef.current?.destroy();
mapRef.current = null;
};
}, []);
return <div id="map" />;
}
The external map object is not React state. The ref provides instance-level storage while the Effect owns synchronization and cleanup.
Do not use refs to avoid stateβ
A dangerous motivation is:
βState re-renders, so I will store everything in refs for performance.β
That makes UI-driving changes invisible to React and encourages mutation-heavy architecture.
const checkoutRef = useRef({
items: [],
discount: null,
customer: null,
});
If the interface depends on those values, refs are the wrong ownership model.
Debugging refsβ
Production example: debounced API requestβ
function SearchInput({onSearch}) {
const timeoutRef = useRef(null);
function handleChange(event) {
const nextQuery = event.target.value;
clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => {
onSearch(nextQuery);
}, 300);
}
return <input onChange={handleChange} />;
}
The timer ID does not need to render. A controlled/displayed query still belongs in state or props.
Exerciseβ
Build a stopwatch with rendered elapsed time in state and the interval ID in a ref. Add Start, Stop, and Reset controls, then explain why those two values use different storage models.
Interview questionsβ
Junior: What is the main difference between useRef and useState?
Mid-level: Why is reading or writing ref.current during render usually unsafe?
Senior: What architecture problems appear when refs are used as a hidden replacement for reactive state?
Summaryβ
Treat refs as escape hatches, not a second state-management system.
Referencesβ
Nextβ
Continue with DOM Refs and Imperative Handles.