Capítulo 56 de 116
useImperativeHandle(ref, createHandle, dependencies?) lets a component customize exactly what a parent's ref receives — instead of exposing the raw underlying DOM node, it exposes a deliberately limited, custom object of methods/values.
useImperativeHandle(ref, createHandle, [deps]) — called inside the child component that receives ref as a prop; createHandle returns the object the parent's ref.current will actually be set to.{ focus(), scrollIntoView() }) keeps the parent's capabilities intentional and limits coupling to the component's internal DOM structure.ref prop on the child: the child component declares a ref parameter (modern React) and passes it into useImperativeHandle — the parent then calls <Child ref={childRef} /> and interacts only through the exposed methods, not the raw node.useMemo/useCallback: the exposed handle object is only recreated when a listed dependency changes, avoiding a fresh object (and thus a changed ref.current identity) on every render.function MyInput({ ref, ...props }) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() { inputRef.current.focus(); },
}));
return <input ref={inputRef} {...props} />;
}
// Parent: myInputRef.current.focus() — only `focus` is exposed, not the raw node
.focus() method without gaining direct access to inputRef's actual DOM node or any other of its properties.createHandle function's dependency array follows the same rules as useMemo/useCallback — list what it actually reads.