Skip to main content

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​

A ref is a persistent mutable pocketThe component can render many times while React preserves the same ref object.
Render 1
Render 2
Render 3
Same ref object
Only 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​

State and refs solve different storage problems
REACTIVEState

Retained between renders Β· setter schedules rendering Β· snapshot per render Β· use for UI-relevant data

IMPERATIVERef

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;
  • AbortController instances;
  • 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.

State update vs ref mutation
setState(next)
Queues a future render; current render keeps its snapshot.
ref.current = next
Mutates immediately; React is not notified.

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​

Stable ref identity across renders
1render 1 β†’ ref A
2render 2 β†’ ref A
3render 3 β†’ ref A
4only .current changes

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.

Lifetime comparison
Local variable
Exists for one function execution.
Ref
Persists for the mounted component instance.
Module variable
Shared outside component instance boundaries.

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​

Where should this value live?
The value affects JSXUse state/reducer/another reactive owner
It must persist across renders but should not trigger renderingA ref may fit
It is an external/imperative object or handleA ref is often appropriate

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​

Ref decision summary
State
React should render when this value changes.
Ref
Persist mutable non-render data for this component instance.

Treat refs as escape hatches, not a second state-management system.

References​

Next​

Continue with DOM Refs and Imperative Handles.