Limitations of React's componentWillUnmount
componentWillUnmount is triggered when a component is about to be destroyed, but if the user directly closes the browser tab, this hook will not be executed.
This issue needs to be considered in specific scenarios. For example, when I was working on WebSocket-related development, the scenario was: when a user enters a details page, they subscribe to an article topic, and when the user navigates to other URLs, the article subscription is canceled. Therefore, I placed the unsubscribe action in componentWillUnmount. However, if the user directly closes the TAB page, the program cannot detect this, leading to bugs.
Why?
Directly closing a tab means immediately destroying the HTML, JS, and CSS resources of that tab page, so React’s lifecycle methods won’t be executed. Therefore, in actual development, it’s important to be aware of this limitation of the hook.
Native window beforeunload Event
The above issue can be complementarily solved using the native window beforeunload event. Example below:
constructor(props) {
super(props);
window.removeEventListener('beforeunload', this.listener);
window.addEventListener('beforeunload', this.listener);
}
listener = function(e) {
console.log('will unmount');
e.returnValue = '';
};
Final Thoughts
- This approach allows executing specified logic even when users directly close the web page.
- While this solution works, it’s important to note that this event should be placed in root components or similar locations. The reason is simple: if it’s bound within looped list components, the overhead would be significant, so this needs attention.
- Although this discussion focuses on React’s componentWillUnmount, similar issues exist with other JavaScript libraries like Angular and Vue.