79262788

Date: 2024-12-08 15:52:02
Score: 2
Natty:
Report link

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.

Reasons:
  • Blacklisted phrase (1): this blog
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): When is the
  • Low reputation (1):
Posted by: Gabor Dicso