Hint
forwardRef passes ref through to a child; useImperativeHandle customizes what the parent sees on that ref
forwardRef — lets a parent component pass a ref to a DOM node or component instance inside a child.
useImperativeHandle — customizes what a parent receives via that ref, exposing only a controlled API instead of the raw DOM node.
// Without forwardRef — parent can't reach inner input
function Input(props) {
return ;
}
// ✅ With forwardRef — parent can call .focus(), etc.
const Input = forwardRef(function Input(props, ref) {
return ;
});
// Parent
function Form() {
const inputRef = useRef(null);
return (
<>
>
);
}
// ─── useImperativeHandle — expose limited API ──────────────────────────────
const FancyInput = forwardRef(function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
clear: () => { inputRef.current.value = ''; },
// Parent can NOT access inputRef.current directly — only these two methods
}));
return ;
});
const ref = useRef();
ref.current.focus(); // ✅
ref.current.value; // ❌ undefined — not exposed