I was wondering if useImperativeHandle
really needed, since I can return the methods I want, with something like a factory function.
For Example, I did this
export function Modal() {
const d = useRef<HTMLDialogElement>(null);
return {
open() {
console.log("open called");
d.current?.showModal()
},
Element({ children }: PropsWithChildren) {
return createPortal(
<dialog ref={d}> {children} </dialog>,
document.getElementById("modal")!
);
}
}
}
instead of using useImperativeHandle
hook to share an API. and the usage can be like this
export function App(){
const modal = Modal()
return (
<div>
<button onClick={modal.open}>click</button>
<modal.Element>
<p>this is a test</p>
</modal.Element>
</div>
)
}
however, I do not know if there is any optimization related functionality provided with useImperativeHandle
hook… and I’m not sure if my way will because any unwanted behavior in big scale