How to use useImperativeHandle to expose component methods
· Category: React
Short answer
useImperativeHandle customizes the instance value exposed when a parent uses ref on your component. It is typically paired with forwardRef.
Steps
- Accept a
refviaforwardRef. - Inside the component, call
useImperativeHandle(ref, () => ({ ... })). - Return an object containing only the methods or properties you want to expose.
Example
const FancyInput = forwardRef((props, ref) => {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
clear: () => { inputRef.current.value = ''; },
}));
return <input ref={inputRef} {...props} />;
});
Tips
- Expose the smallest surface area possible.
- Prefer props over imperative APIs whenever you can.
- Remember that refs should not hold reactive data; use state for that.