I have a popup and I want that popup to be enabled for 3s. So I used setTimeout for 3s. Now I want to clear the timeout if the screeen is unmounted. But using this is giving me warning on lighthouse that unload is deprecated.
Any alternative of cleanup function ?
useEffect(() => {
return () => {
clearTimeout(popupTimeoutId);
};
}, []);
I am using cleanup function but needs a solution that can help me remove the lighthouse warning.
There is no React useEffect
hook cleanup function alternative. The Lighthouse deprecation/warning has nothing to do with the useEffect
hook though. It would seem that somewhere in your app you have instantiated a window.unload
event listener, which is a deprecated API.
There was also a deprecation warning from Chrome: Deprecating the unload event.
I would suggest switching to the beforeunload event, though the above Chrome page suggests also trying/using visibilitychange and pagehide events as Alternatives to unload events.
Instead of unload it is recommended to use:
- visibilitychange: To determine when the visibility of a page changes. This event happens when the user switches tabs, minimizes the browser window, or opens a new page. Consider the hidden state the last reliable time to save app and user data.
- pagehide: To determine when the user has navigated away from the page. This event happens when the user navigates away from the page, reloads the page, or closes the browser window. The pagehide event is not fired when the page is simply minimized or switched to another tab. Note that, as pagehide does not make a page ineligible for the back/forward cache, it is possible a page can be restored after this event fires. If you're cleaning up any resources in this event, then they may have to be restored on page restore.
The beforeunload event has a slightly different use case to unload in that it is a cancellable event. It is often used to warn users of unsaved changes when navigating away. This event is also unrealiable as it will not fire if a background tab is killed. It is recommended to limit use of beforeunload and only add it conditionally. Instead, use the above events for most unload replacements.
At the end of the day though, this is still just a warning, and you are free to ignore it with the understanding that your app/page may not function properly or as you expect in some browsers.