Memory leak when a iframe with url pointing to a react app is removed and added

882 Views Asked by At

I have a react-redux app which runs inside iframe, Iframe with same exact url is getting removed and added back by the parent application but doing so is causing memory footprint and CPU usage growing as we keep doing more number of times (reaches 5 GB after trying around 100 times), I believe it may not be something related to just react but in general as well, any help would be much appreciated.

React App in iframe:

const postMessage = () => {
    window.parent.postMessage(JSON.stringify({ type: "TYPEB", message: "some message to parent" }), location.origin);
}
const messageEventHandler = (event) => {
    //event handling code
}
const addMessageEventListenerFromParent = () => {
    window.addEventListener("message", messageEventHandler);
};

const rootComponent = () =>
    useEffect(() => {
        // adding event listeners
        addMessageEventListenerFromParent();
        postMessage();
        return () => {
            console.log("unmounting the app");
            removeMessageEventListenerFromParent();
        };
    }, []);
}

Parent App (React app):

const Iframe = (props) => {
    const iframeRef = useRef(null);

    const postMessage = (message) => {
        if (iframeEl?.current.contentWindow?.postMessage) {
            iframeEl.current.contentWindow.postMessage(message, location.origin);
        }
    };

    useEffect(() => {
        postMessage({
            type: "TYPEA",
            payload: somePayload,
        })
    }, [props.propA])

    const memoizedIframe = useMemo(() => (
        <iframe ref= { iframeRef } key = { key } className = "iframetask" src = { sourceUri } />
        ), [inputs]);
    return memoizedIframe;
}

export default memo(Iframe);

This is a sample code of my app (running in iframe), return function (cleanup function) not getting executed when the iframe is removed and added back by parent app, this means the component is not getting unmounted but getting mounted as iframe is re-inserted.

0

There are 0 best solutions below