useImperativeHandle for Custom Ref APIs
What You'll Learn
You'll learn how to customize what a parent component receives when it uses a ref on your component, instead of exposing the raw DOM element.
The Problem with Forwarding Raw Refs
When you use forwardRef, the parent gets direct access to the underlying DOM node. Sometimes this is too much power—the parent could call any DOM method, potentially breaking your component's internal logic. You might want to expose only specific methods or values.
What useImperativeHandle Does
useImperativeHandle lets you customize the ref object. Instead of the parent receiving the raw DOM element, you decide exactly what the ref exposes—usually a custom object with specific methods.
Analogy: It's like a hotel room service menu. Instead of giving guests full access to the kitchen (raw DOM), you provide a curated list of options (specific methods).
Basic Pattern
import { forwardRef, useRef, useImperativeHandle } from 'react';
const FancyInput = forwardRef<{ focusAndSelect: () => void }, {}>(
(props, ref) => {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
focusAndSelect: () => {
inputRef.current?.focus();
inputRef.current?.select();
}
}));
return <input ref={inputRef} />;
}
);
Now the parent can call myRef.current.focusAndSelect() but cannot directly access the DOM element. You've created a controlled API.
When to Use This
Use useImperativeHandle when you need to expose specific imperative actions (like focus, play, or reset) while hiding internal implementation details from the parent.
Key Takeaway: useImperativeHandle customizes what the parent receives on a forwarded ref, letting you expose a controlled API instead of the raw DOM element.