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?
ReactJS componentWillUnmount() MethodThe componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e before the component gets unmounted.
componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount() .
To handle the browser tab close even in React: Use the useEffect hook to add an event listener. Listen for the beforeunload event. The beforeunload event is triggered when the tab is about to be unloaded.
ReactJS – componentWillUnmount() Method This method is called during the unmounting phase of the React Lifecycle, i.e., before the component is destroyed or unmounted from the DOM tree. This method is majorly used to cancel all the subscriptions that were previously created in the componentWillMount method.
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.
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) { ... };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With