score:0

Accepted answer

welcome to so!

i think you have unintentionally destructured your function using the {}.

try this:

useeffect(() => {
  window.addeventlistener("beforeunload", handleunload);

  return () => window.removeeventlistener("beforeunload", handleunload);
}, [handleunload]);

i've added [handleunload] to the 2nd attribute of useeffect to prevent it adding and removing the event listener upon every state change.

score:2

try using a ref:

const useunload = (fn) => {
  const cb = react.useref(fn);

  react.useeffect(() => {
    const onunload = cb.current;
    window.addeventlistener('beforeunload', onunload);
    return () => {
      window.removeeventlistener('beforeunload', onunload);
    };
  }, [cb]);
};

and then use this to call

useunload((e) => {
  e.preventdefault();
  console.log('hey')
  alert("hey");
});

More Query from same tag