Sp-dev-docs: In a React Sharepoint Framework webpart, the ComponentWillUnmount is not invoked when the webpart is deleted from the Page.

Created on 31 Mar 2018  路  2Comments  路  Source: SharePoint/sp-dev-docs

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.

spfx-general tracked bug-confirmed

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.

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings