When is the window.addEventListener()
call executed? Does the problem occur on mobile, or desktop? You may want to use the visibilitychange
event instead (or both). See this blog post.
That said, I've used the beforeunload
event successfully with the below approach:
const unload = useCallback((e) => {
// ...
}, []);
useEffect(() => {
window.addEventListener("beforeunload", unload);
return () => {
window.removeEventListener("beforeunload", unload);
}
}, [unload]);
My unload
function does not contain an async API call though, which may be a significant difference between our use cases.