What is it?
useImperativeHandle customizes the instance value that is exposed to parent components when using ref.
Normally, you shouldn't need this. React flows data down via props. But sometimes, you need to imperatively trigger a child function (like scrollBy, focus, or playVideo).
Syntax
It must be used with forwardRef.
import { forwardRef, useImperativeHandle, useRef } from 'react';
const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
// We only expose these two methods to the parent
// The parent CANNOT access the real DOM node or other internals
alertHi: () => alert('Hi'),
focus: () => inputRef.current.focus(),
}));
return <input ref={inputRef} />;
});
Usage in Parent
function Parent() {
const ref = useRef();
return (
<>
<CustomInput ref={ref} />
<button onClick={() => ref.current.alertHi()}>
Trigger Child Alert
</button>
</>
);
}
Best Practices
Avoid this hook. It breaks the declarative nature of React. Only use it for:
- Managing focus / selection / media playback.
- Triggering imperative animations.
- Integrating with third-party DOM libraries.
Sponsored Content
Google AdSense Placeholder
CONTENT SLOT