Cannot access HTML DOM in react useEffect return function, for cleanup

80 Views Asked by At

I am using a 3rd Party script in my react app, that script is using pure JS to append HTML elements in my webpage. The library attaches a mw function to the window object and we can then perform various operations like 'init' and 'cleanup'.

The init function runs pretty normally and shows a widget UI, but the clenup function is trying to access dom to removeEventListeners but cannot find the dom.

Code:

const ThirdPartyWidget = () => {

  useEffect(() => {
    if (window.mw) {
      window.mw("init", { elementId: "widget-element" });
    }

    return () => {
      if (window.mw) {
        window.mw("cleanup");
      }
    };
  }, []);

  return <div id="widget-element"></div>;
};

export default ThirdPartyWidget;

I am getting the following error,

enter image description here

What i know is the cleanup function is trying to access the dom and remove eventlisteners that it had attached. But it is not able to do so.

The library is accessing the correct DOM element as when i try to access the DOM using the same querySelector path in chrome dev tools console i can access them. There is something that i am missing in the core concepts of react lifecycle and cleanups that is causing the problem.

What can i do now?

Main Question Here is >> Does react run the useEffect cleanUp return function after clearing up the DOM for that component?

PS. useRef and DOM references cannot be used here sadly as it is a 3rd Party LIB.

0

There are 0 best solutions below