J.E.C.
J.E.C.

Reputation: 3012

Why doesn't componentWillUnmount trigger when closing the window?

One would think that componentWillUnmount() in react would trigger when closing the application. According to the docs, componentWillUnmount() is triggered when unmounting it or if it's relative component is being destroyed. Why doesn't closing the window or tab unmount the component?

Upvotes: 14

Views: 9252

Answers (2)

joshwilsonvu
joshwilsonvu

Reputation: 2689

React would do that if it could, but think about it: closing the browser window means discarding all of the HTML, CSS, and JS on the page. Even if it tapped into the onbeforeunload event, it would be a waste to go about unmounting every component when they are about to be discarded anyway, and it would slow down closing the page. There historically hasn't been a good way to run any code when the tab is closed.

However, there is an experimental API called the Beacon API that attempts to solve this problem, in the case that you want to send data over the network when the browser is closed.

Upvotes: 10

Dennis Vash
Dennis Vash

Reputation: 53884

The Mounting term refers to actions on the DOM.

Lifecycle methods are custom functionality that gets executed during the different phases of a component. There are methods available when the component gets created and inserted into the DOM (mounting), when the component updates, and when the component gets unmounted or removed from the DOM.

Closing the window/tab fires the browser onbeforeunload event:

These events fire when a window is about to unload its resources.

window.addEventListener("beforeunload", function(event) { ... });
window.onbeforeunload = function(event) { ... };

Upvotes: 6

Related Questions