DOM refs and imperative handles
React normally manages the DOM for you. Refs are the controlled escape hatch for browser operations that are inherently imperative, such as focus, scrolling, measurement, media control, and third-party widget integration.
Getting a DOM nodeโ
import {useRef} from 'react';
function Search() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current?.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={handleFocus}>Focus search</button>
</>
);
}
React assigns the committed DOM node to inputRef.current.
Render versus commit matters for refsโ
Reading a DOM ref during render is generally wrong because the DOM for that render has not been committed yet.
Common imperative DOM actionsโ
Focusโ
function LoginForm() {
const emailRef = useRef(null);
function handleInvalidSubmit() {
emailRef.current?.focus();
}
return (
<form>
<input ref={emailRef} type="email" />
<button type="button" onClick={handleInvalidSubmit}>Focus email</button>
</form>
);
}
Programmatic focus should help the user understand or complete an action, not jump unexpectedly.
Scrollingโ
function ProductCard() {
const detailsRef = useRef(null);
function handleShowDetails() {
detailsRef.current?.scrollIntoView({behavior: 'smooth'});
}
return (
<>
<button onClick={handleShowDetails}>Show details</button>
<section ref={detailsRef}>...</section>
</>
);
}
Media APIsโ
function VideoPlayer() {
const videoRef = useRef(null);
return (
<>
<video ref={videoRef} src="/demo.mp4" />
<button onClick={() => videoRef.current?.play()}>Play</button>
<button onClick={() => videoRef.current?.pause()}>Pause</button>
</>
);
}
Measurementโ
function Panel() {
const panelRef = useRef(null);
function measure() {
const rect = panelRef.current?.getBoundingClientRect();
console.log(rect?.width);
}
return (
<>
<div ref={panelRef}>Panel</div>
<button onClick={measure}>Measure</button>
</>
);
}
If a measurement must drive a visual adjustment before paint, useLayoutEffect may be needed; use it deliberately because it can block painting.
Callback refsโ
A ref can also be a function:
<div
ref={node => {
console.log('node', node);
}}
/>
Callback refs are useful for dynamic collections.
function ProductList({products}) {
const itemRefs = useRef(new Map());
return products.map(product => (
<article
key={product.id}
ref={node => {
if (node) itemRefs.current.set(product.id, node);
else itemRefs.current.delete(product.id);
}}
>
{product.name}
</article>
));
}
Callback ref cleanupโ
Modern React allows a ref callback to return cleanup:
<li
ref={node => {
const map = itemsRef.current;
map.set(item.id, node);
return () => {
map.delete(item.id);
};
}}
>
{item.name}
</li>
Avoid destructive DOM mutationโ
React owns the DOM structure it renders.
Risky:
containerRef.current.innerHTML = '';
This can make the real DOM disagree with React's model. Prefer non-destructive actions such as focus, scroll, measurement, media methods, or integration with DOM regions that React does not manage directly.
Passing refs to components in React 19โ
React 19+
Function components can receive ref as a prop.
function MyInput({label, ref}) {
return (
<label>
{label}
<input ref={ref} />
</label>
);
}
const inputRef = useRef(null);
<MyInput ref={inputRef} label="Email" />;
forwardRef remains maintenance knowledge for older React code and libraries, but new React 19 function components can use the ref prop model directly.
Raw DOM node versus narrow imperative handleโ
Exposing a raw node gives the parent every DOM capability. Often the component should expose much less.
getInternalState ยท setInternalState ยท mutateCache ยท forceRefresh ยท rewrite DOM
focus() ยท selectAll() ยท scrollToError()
useImperativeHandleโ
useImperativeHandle customizes what a component exposes through its ref.
import {useImperativeHandle, useRef} from 'react';
function SearchInput({ref}) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current?.focus();
},
clear() {
if (inputRef.current) inputRef.current.value = '';
},
}), []);
return <input ref={inputRef} />;
}
Parent:
function Toolbar() {
const searchRef = useRef(null);
return (
<>
<SearchInput ref={searchRef} />
<button onClick={() => searchRef.current?.focus()}>Focus</button>
</>
);
}
Prefer props for declarative behaviourโ
A declarative model is usually better when state can describe the UI.
<Modal open={isOpen} />
Use an imperative API when the behaviour itself is imperative, such as focus, scrolling, selection, or media control.
Common mistake: refs as ordinary state communicationโ
Avoid reading child business state through a ref:
childRef.current.selectedTab;
If selectedTab affects rendered UI or parent logic, prefer controlled state:
<Tabs value={selectedTab} onChange={setSelectedTab} />
Common mistake: global DOM query instead of ownershipโ
document.querySelector('#email').focus();
A ref keeps the relationship local to the component tree:
const emailRef = useRef(null);
<input ref={emailRef} />;
Integrating third-party widgetsโ
function Chart({data}) {
const containerRef = useRef(null);
const chartRef = useRef(null);
useEffect(() => {
chartRef.current = createChart(containerRef.current);
return () => {
chartRef.current?.destroy();
chartRef.current = null;
};
}, []);
useEffect(() => {
chartRef.current?.setData(data);
}, [data]);
return <div ref={containerRef} />;
}
Debugging refsโ
If a DOM ref is null, check whether the element is rendered, whether you are reading before commit, whether conditional rendering removed it, whether the ref reaches the correct node/component, and whether callback-ref cleanup removed it.
Exerciseโ
Build a reusable SearchInput that receives ref as a prop, keeps the actual DOM node private, and exposes only focus() and selectAll() through useImperativeHandle.
Interview questionsโ
Junior: When would you use a DOM ref?
Mid-level: Why should you avoid reading DOM refs during render?
Senior: When is an imperative handle a better API than exposing a raw DOM node, and when should both be avoided in favour of props/state?
Summaryโ
Referencesโ
- https://react.dev/learn/manipulating-the-dom-with-refs
- https://react.dev/reference/react/useImperativeHandle
- https://react.dev/reference/react/forwardRef
- https://react.dev/blog/2024/12/05/react-19
Nextโ
Continue with Custom Hooks.