Skip to main content

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โ€‹

When does a DOM ref become usable?The next DOM node does not exist as committed UI during render.
1Render calculates next UI
2React commits DOM changes
3DOM refs are updated
4Events / Effects can use the node

Reading a DOM ref during render is generally wrong because the DOM for that render has not been committed yet.

Common imperative DOM actionsโ€‹

Healthy DOM-ref use cases
Focus
Move keyboard focus after a user-relevant transition.
Scroll
Call scrollIntoView for a specific owned node.
Measure
Read geometry after commit.
Media
Play, pause, seek, or inspect media APIs.
Observer / widget
Connect imperative browser or third-party systems.
Custom handle
Expose a narrow imperative API instead of the raw node.

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>
Callback-ref lifecycle
1node commits
2ref callback receives node
3register imperative relationship
4node leaves / ref changes
5cleanup removes registration

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.

Prefer the smallest imperative surfaceExpose the capability the parent needs, not the implementation object.
RAW / LEAKYToo broad

getInternalState ยท setInternalState ยท mutateCache ยท forceRefresh ยท rewrite DOM

CAPABILITYNarrow handle

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>
</>
);
}
Imperative handle boundary
Parent
Needs a small imperative capability.
Component API
Exposes focus() / clear(), not the raw implementation.
Private DOM node
The component keeps ownership of the actual input.

Prefer props for declarative behaviourโ€‹

A declarative model is usually better when state can describe the UI.

<Modal open={isOpen} />
Declarative before imperative
State
Component
UI

Use an imperative API when the behaviour itself is imperative, such as focus, scrolling, selection, or media control.

Should this interaction use props/state or a ref?
The value describes what UI should existPrefer state + props
The action is inherently imperative browser behaviourA DOM ref may fit
A parent needs only a tiny subset of child capabilitiesExpose a narrow useImperativeHandle API

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} />;
}
Healthy third-party widget integration
1React commits host node
2DOM ref exposes container
3Effect creates widget
4data Effect synchronizes updates
5cleanup destroys widget

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โ€‹

DOM refs summary
1React owns DOM structure
2Refs expose controlled imperative access
3React 19 supports ref as a prop
4useImperativeHandle narrows the API

Referencesโ€‹

Nextโ€‹

Continue with Custom Hooks.