I am writing an hook that receives an HTMLElement as argument. I would like to make it so that it can accept even just an id and then find the element on its own.
I run document.getElementById() inside an useEffect in the hook.
In this way the DOM is queried only after the component calling the hook has been rendered in the actual DOM.
And I save the element straight away in react ref.
If I run my app and navigate to render the component with the hook, everything works perfectly. But if I continue to navigate so that the component is unmounted and then I navigate back to mount it again, the app crashes.
After a little digging I found the problem to be that, while the element returned by document.getElementById is the same in both cases (because the id is the same), Node.isConnected returns true in the first case and false when the crash occurs.
Anyone knows what may cause this difference?
Note that after the first successful mount, the component is unmounted and mounted brand new.
Ps: it would be great if you could provide a theoretical answer rather than requiring a minimal reproducible example, as at the moment I don't have access to my laptop, and yet I can't stop obsessing myself with this problem.