Imperative resource handles
Keep an interval, timeout, subscription, or animation-frame handle across renders without causing UI updates.
React 19+ · Type Alias
MutableRefObject is the pre-React-19 TypeScript concept for a ref whose current value can be assigned. In React 19, useRef returns the unified mutable RefObject shape instead; useRef requires an initial argument.
In React 19, refs returned by useRef are mutable objects with a current property. React preserves the same object between renders, while changes to current do not trigger rendering, making refs suitable for values such as timer handles or DOM nodes that are not themselves rendered.
const ref = useRef(initialValue)| Name | Type | Description |
|---|---|---|
initialValue | any | The value assigned to the ref object's current property initially; it may have any type and is ignored after the initial render. |
An object with a single mutable current property. It initially contains initialValue, and React returns the same object on subsequent renders.
import { useRef } from 'react';
export default function Stopwatch() {
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
function start() {
if (intervalRef.current === null) {
intervalRef.current = setInterval(() => {}, 1000);
}
}
function stop() {
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}
return <button onClick={intervalRef.current ? stop : start}>Toggle</button>;
}Stores an interval handle across renders and updates it without triggering a render.
Keep an interval, timeout, subscription, or animation-frame handle across renders without causing UI updates.
Hold a DOM node for focus, measurement, scrolling, or other browser API operations.
Retain the latest non-rendering value for an event handler or effect.
useRef returns an object with a current property. React returns the same object on later renders, and changing current does not cause a re-render.
Follow-up: When should state be preferred? Use state when a value participates in rendered output or its change must cause React to render again.
Pass the initial value to useRef at the top level of the component. The returned object's current property starts with that value and can later be assigned another value.
Follow-up: What happens to the initial argument after mounting? React ignores it after the initial render, so it is not a per-render reset mechanism.
Refs are useful for information not needed for rendering, including DOM nodes and timeout IDs. They provide an escape hatch for interacting with browser APIs and other non-React systems.
Follow-up: What should hold UI-visible data? Store it in state so React can schedule the corresponding update to the rendered result.
useRefuseImperativeHandleref