useImperativeHandle
is a React hook that allows a child component to expose an imperative API to a parent component. "Imperative" here refers to a direct order or command.
To use imperative handle, the child component must call useImperativeHandle
in its render method and pass in a reference to the parent component. The child can then define the imperative API by returning an object from the useImperativeHandle
call. The parent can access this API by using the ref prop on the child component.
Here is an example of how to use useImperativeHandle
:
// Child component
const Modal = ({forwardedRef}) => {
const [isOpen, setIsOpen] = useState(false)
useImperativeHandle(forwardedRef, () => ({
open: () => {
setIsOpen(true);
},
close: () => {
setIsOpen(false);
}
}))
return (
<div>
<button onClick={() => setIsOpen(false)}>Close</button>
<p>Modal content</p>
</div>
)
}
export default forwardRef(Modal)
// Parent component
const App = () =>{
const modalRef = useRef(null);
const handleOpen = () => {
modalRef.current.open();
}
return (
<div>
<p>Parent</p>
<Modal forwardedRef={modalRef}/>
<button onClick={handleOpen}>Open</button>
</div>
);
}
In this example, the Modal
component uses useImperativeHandle
to define an imperative API for the parent App
component to use. The App
component can now use the ref prop to open the Modal
component. This allows the App
component to control the state of the Modal
component without re-rendering the whole parent component.
One example of where this might be useful is when you have a custom input component that needs to be controlled by a parent form. The input component might have internal state for managing focus, selection, and other aspects of user interaction. The parent form can use imperative handle to access this state and update the input as necessary, and not worry about every other child component in the parent component re-rendering with the form changes.
Another example is when you have a complex animation or transition that is implemented in a child component. The parent can use imperative handle to trigger the animation or transition and control its behavior. This allows the parent to have full control over the animation without having to know the details of how it is implemented in the child.
useImperativeHandle
is a useful tool for creating reusable components that can be easily integrated into a parent component. It allows the child to expose a specific API to the parent, while keeping its internal implementation hidden. This helps to maintain the separation of concerns between the child and parent.
Top comments (0)