What are useImperativeHandle and forwardRef?
Hint
forwardRef passes ref through to a child; useImperativeHandle customizes what the parent sees on that ref
Full Answer
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 <input {...props} />;
}
// ✅ With forwardRef — parent can call .focus(), etc.
const Input = forwardRef(function Input(props, ref) {
return <input ref={ref} {...props} />;
});
// Parent
function Form() {
const inputRef = useRef(null);
return (
<>
<Input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
>
);
}
// ─── 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 <input ref={inputRef} {...props} />;
});
const ref = useRef();
ref.current.focus(); // ✅
ref.current.value; // ❌ undefined — not exposed
💡 Use forwardRef sparingly — it tightly couples parent to child internals. Most of the time you can solve the problem with a controlled component pattern instead. Use it mainly for UI library components (inputs, modals). In React 19, function components receive
ref as a regular prop, so new code rarely needs forwardRef.More Hooks Questions
Practice this in a timed sprint
5 free questions, no signup required