A ref passed to a custom component does not automatically reach a DOM node inside it. forwardRef lets a component receive a ref and attach it to a child element. useImperativeHandle customizes what that ref exposes.
A ref passed to a custom component does not automatically reach a DOM node inside it. forwardRef lets a component receive a ref and attach it to a child element. useImperativeHandle customizes what that ref exposes.
const TextInput = forwardRef(function TextInput(props, ref) {
return <input ref={ref} {...props} />; // parent's ref now points to the <input>
});
// parent can focus the inner input:
const ref = useRef(null);
<TextInput ref={ref} />;
// ref.current.focus();
Sometimes you don't want to leak the whole DOM node — only specific methods:
const FancyInput = forwardRef(function FancyInput(props, ref) {
const inner = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => inner.current.focus(),
clear: () => { inner.current.value = ""; },
}), []);
return <input ref={inner} {...props} />;
});
// parent: fancyRef.current.focus(); fancyRef.current.clear();
Prefer props/state for communication. Reach for refs only for genuinely imperative needs: focus management, scrolling, text selection, media playback, or integrating imperative libraries. Note: in React 19, ref can be passed as a normal prop, so forwardRef is often no longer required.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate