Q26: What is forwardRef and useImperativeHandle, and when should you use them?
forwardRef allows a component to pass a ref down to a child component. useImperativeHandle works with forwardRef to customize the imperative handle (methods/properties) exposed to the parent component, hiding internal implementation details.
Custom Imperative Methods via useImperativeHandle
const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focusInput: () => inputRef.current.focus()
}));
return <input ref={inputRef} />;
});Parent components calling ref.current.focusInput() execute the custom imperative handle.
Key Takeaways
forwardRefpasses refs down through child functional components.useImperativeHandlelimits exposed imperative methods (e.g. exposing.focus()instead of full DOM element).
Knowledge Check
What is the main reason to pair useImperativeHandle with forwardRef?