Imagine you make a super fancy input component as part of your design system. Imagine that a parent element (i.e. the component that renders the fancy input) that needs to call focus()
on the fancy input because of a validation error.
This is what useImperativeHandle
is for. It allows a child component to expose a method (I used focus as an example but could be anything). You pass in a ref from useRef
to the child component, it uses that ref to pass back methods to the parent. If you make libraries or design systems, this is useful. Otherwise there are easier ways to do this.
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
useImperativeHandle
customizes the instance value that is exposed to parent components when using ref
. As always, imperative code using refs should be avoided in most cases. useImperativeHandle
should be used with forwardRef