Direct DOM access with refs
Attaching a ref to a DOM element, React 19's ref-as-prop versus forwardRef, useImperativeHandle, focus management, and when reaching into the DOM is right.
Direct DOM access with refs
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Passing a ref as the ref prop on a DOM element — <input ref={inputRef} /> — makes React set inputRef.current to the actual DOM node once it's mounted, giving you direct, imperative access to it.
- Before React 19, a component couldn't just accept a ref prop and forward it to its own DOM node; it had to be wrapped in forwardRef, which took (props, ref) and attached the ref itself.
- React 19 lets function components accept ref as a plain prop, the same way they accept any other prop, which makes forwardRef unnecessary for new code — but existing code built with forwardRef still works and you'll see it everywhere.
- useImperativeHandle lets a component expose a deliberately limited, custom set of methods through a ref — like focus() or scrollIntoView() — instead of handing out the raw DOM node or every internal detail.
- Managing focus (moving it to an input after an error, or into a modal when it opens) is one of the few places reaching into the DOM directly is the correct, idiomatic choice rather than a workaround.
- Reaching for a ref to read or set text content, classes, or styles that React's own state and props could drive is usually the wrong call — it creates a second source of truth that can drift out of sync with what React thinks is on screen.
Getting a handle on the real element
React normally hides the DOM from you — you describe what should be on screen, and reconciliation figures out the actual DOM updates. A ref is the escape hatch: attach one to a JSX element, and after that element mounts, the ref’s current holds the literal DOM node.
function SearchInput() {
const inputRef = useRef(null);
function handleFocusClick() {
inputRef.current.focus(); // calling a real DOM method directly
}
return (
<>
<input ref={inputRef} type="text" />
<button onClick={handleFocusClick}>Focus the input</button>
</>
);
}
inputRef.current is a genuine HTMLInputElement, not a React abstraction — .focus(), .value, .scrollIntoView(), and every other DOM API are all there, exactly as they would be if you’d grabbed the element with document.querySelector. The difference is React handed it to you at the right moment, already synced to the element it actually rendered.
Passing refs through to a child: forwardRef, then React 19
The example above attaches a ref to a plain <input>, a built-in DOM element, which always accepts a ref prop. The trouble starts when you want to attach a ref through your own component to a DOM node somewhere inside it. For years, a function component simply ignored a ref prop — it wasn’t passed through like other props — so React needed a dedicated API, forwardRef, to opt a component into accepting one:
// The forwardRef way — still extremely common in existing code
const FancyInput = forwardRef(function FancyInput(props, ref) {
return <input ref={ref} className="fancy" {...props} />;
});
function Form() {
const inputRef = useRef(null);
return <FancyInput ref={inputRef} />;
}
React 19 removes the need for this ceremony: a function component can declare ref as an ordinary prop, right alongside everything else, and it just works.
// React 19 — ref is a plain prop, no forwardRef needed
function FancyInput({ ref, ...props }) {
return <input ref={ref} className="fancy" {...props} />;
}
function Form() {
const inputRef = useRef(null);
return <FancyInput ref={inputRef} />;
}
Both patterns do the same thing, and you will run into forwardRef constantly in existing codebases, libraries, and tutorials written before this change — it isn’t deprecated or removed, just no longer necessary for code you write today. Knowing both matters: you need to recognize forwardRef to read older code, and you should reach for the plain-prop form in anything new.
Limiting what a ref can do: useImperativeHandle
Handing out the raw DOM node, as both examples above do, means the parent can do anything to it — set arbitrary styles, remove attributes, call any method. Sometimes that’s too much access. useImperativeHandle lets a component expose a narrow, custom API through the ref instead:
function FancyInput({ ref, ...props }) {
const internalRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
internalRef.current.focus();
},
clear() {
internalRef.current.value = "";
},
}));
return <input ref={internalRef} {...props} />;
}
function Form() {
const inputRef = useRef(null);
return (
<>
<FancyInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
<button onClick={() => inputRef.current.clear()}>Clear</button>
</>
);
}
Now inputRef.current isn’t the raw <input> element at all — it’s the plain object { focus, clear } that useImperativeHandle constructed. The parent can call exactly those two methods and nothing else; it can’t reach in and, say, change the input’s type attribute. This is the same instinct as a well-designed function signature: expose the smallest API that does the job, not the entire internal implementation.
Focus management: the case where this is clearly right
Moving keyboard focus is the textbook example of something only a direct, imperative DOM call can do — there’s no prop you can set that means “please focus this element right now”:
function Modal({ isOpen, onClose }) {
const closeButtonRef = useRef(null);
useEffect(() => {
if (isOpen) {
closeButtonRef.current.focus(); // move focus into the modal when it opens
}
}, [isOpen]);
if (!isOpen) return null;
return (
<div role="dialog" aria-modal="true">
<button ref={closeButtonRef} onClick={onClose}>
Close
</button>
{/* modal content */}
</div>
);
}
This isn’t a workaround — it’s the correct, idiomatic tool. Accessibility guidance for dialogs and form-validation errors specifically calls for moving focus, and refs are how React code does that.
When reaching into the DOM is the wrong call
The anti-pattern version of this lesson is using a ref to read or write something React’s own state already controls — toggling a CSS class, setting textContent, or reading an input’s value on every keystroke instead of using a controlled value and onChange. Doing that creates two competing sources of truth: what React believes should be rendered, and whatever the ref mutated directly, and the two can drift apart in ways that are hard to debug. The rule of thumb from this lesson and the previous one holds here too: if React’s declarative model — state, props, conditional rendering — can express what you want, use that. Reach for a ref only for the genuinely imperative leftovers: focus, measurement, scrolling, and native methods that have no declarative equivalent.
What the video covers
Developer Way’s video covers the full arc this lesson teaches in one pass: attaching a ref to a DOM element, the history of forwardRef and React 19’s simplification of it, and useImperativeHandle for exposing a deliberate imperative API. It’s a companion piece to Nadia Makarevich’s widely-read “Advanced React” writing on the same topics. The focus-management framing and the explicit anti-pattern warning above go a bit further than the video’s own scope.
Where this fits
This closes out the effects-and-refs group. Everything here — synchronizing with the outside world, cleaning up correctly, and holding mutable values and DOM nodes in refs — becomes the foundation for the next group’s concern: understanding why components re-render at all, starting with why React re-renders.
Check yourself
What does React do when you pass a ref to a DOM element's ref prop?
Once that element is mounted in the actual DOM, React sets the ref's current property to that real DOM node, giving the component a direct handle to call methods on it or read its properties, outside of React's normal render cycle.
Why did forwardRef exist before React 19, and what changed?
A ref passed to a function component wasn't automatically forwarded to anything inside it, so forwardRef existed to let a component explicitly accept a ref as a second argument and attach it to one of its own elements; React 19 lets function components simply declare ref as an ordinary prop, so forwardRef is no longer necessary for new components, though it still works for existing ones.
What problem does useImperativeHandle solve?
It lets a component control exactly what a parent can do through a ref to it, exposing a small, deliberate set of methods like focus() instead of handing over the entire underlying DOM node and letting the parent manipulate it however it wants.
When is reaching directly into the DOM through a ref the right call, rather than an anti-pattern?
When the task is something React's declarative model doesn't cover well, like moving keyboard focus to a specific element, measuring an element's size, or triggering a native method such as play() on a video — cases outside what state and props can express, rather than a substitute for them.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.