I'm facing issue with the React web part I have in my solution. The ComponentWillUnmount event is not invoked when I delete the web part from the page.
To repro this issue, I have created a dummy webpart, which writes some stuff to the console log when it is unmounted (I am assuming here that whenever we remove a SPFX React web part, it should call ComponentWillUnmount handler). In my case, it is not logging the stuff to the console window.
You can refer the code here https://github.com/yoghcl/reactUnMount
Please let me know if I am missing something.
I'm betting the reason why this is occurring is that your React Component isn't being unmounted (duh). The reason why is that SPFx doesn't do this automatically, as it's UI Framework neutral. The HelloWorld example and nearly all samples out there I've seen also miss a critical piece that you need.
Add this to your web part.ts file:
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
The above should really be added to all the samples on spdev-docs. Maybe I'll submit some pull requests. A good way to see the behavior working (and not) is to fire up the React dev tools in Chrome. You'll notice as you add and remove a SPFx web part from the workbench, it's never removed from the Chrome dev tools.
Thanks Jon, it worked for me.
Most helpful comment
I'm betting the reason why this is occurring is that your React Component isn't being unmounted (duh). The reason why is that SPFx doesn't do this automatically, as it's UI Framework neutral. The HelloWorld example and nearly all samples out there I've seen also miss a critical piece that you need.
Add this to your web part.ts file:
protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); }
The above should really be added to all the samples on spdev-docs. Maybe I'll submit some pull requests. A good way to see the behavior working (and not) is to fire up the React dev tools in Chrome. You'll notice as you add and remove a SPFx web part from the workbench, it's never removed from the Chrome dev tools.