External DOM integration
Register or unregister a DOM node with an external system when it appears or disappears.
React 19+ · Type Alias
RefCallback is the function form of a React ref. React calls it with the attached DOM node and, in React 19, can run a cleanup function returned by the callback when the node detaches.
RefCallback is the callback form of a React ref. React invokes it with the referenced value when attaching, and in React 19 a returned cleanup function runs when the ref detaches; if no cleanup is returned, React uses null for detachment.
(node: T | null) => void | (() => void)| Name | Type | Description |
|---|---|---|
node | DOM node | The referenced DOM node supplied when the callback ref attaches; the page documents this as a DOM node. |
An optional cleanup function. React calls it when the ref is detached; if omitted, React calls the callback with null on detachment.
import { useState } from 'react';
export default function App() {
const [node, setNode] = useState<HTMLInputElement | null>(null);
return (
<label>
Name
<input
ref={(element) => {
setNode(element);
return () => setNode(null);
}}
/>
<span>{node ? 'Attached' : 'Detached'}</span>
</label>
);
}The callback receives the input element when React attaches the ref and returns cleanup that runs when React detaches it.
Register or unregister a DOM node with an external system when it appears or disappears.
Measure, focus, observe, or otherwise act on a node immediately after attachment.
Track a dynamic collection of nodes where each item needs attachment-specific registration.
A callback ref is a function passed to ref instead of a ref object. React calls it with the DOM node when attached; in React 19, the callback can return cleanup that runs when detached.
Follow-up: What happens without returned cleanup? React calls the callback with null on detachment, so code must handle that value or use the React 19 cleanup form.
React compares callback identity. If a different callback is supplied, React cleans up the old ref and attaches the new one; an inline function can therefore cause repeated setup during rerenders.
Follow-up: How can repeated work be avoided? Reuse the callback function reference, for example by defining it stably or memoizing it when appropriate.
Callback refs need symmetric cleanup because setup may run more than once in development Strict Mode. Returning cleanup that reverses subscriptions, registrations, or other effects prevents leaks and exposes bugs early.
Follow-up: What kind of bug does missing cleanup cause? External registrations can accumulate across setup cycles, producing stale references, memory leaks, or duplicated behavior.
useRefcreateRefuseImperativeHandleStrictModeref