Angelos Orfanakos

Custom React hook to prevent window unload

I recently needed a way to prevent the window/tab from closing if there were unsaved changes in an application and came up with the following simple, custom React hook:

function usePreventWindowUnload(preventDefault) {
  React.useEffect(() => {
    if (!preventDefault) return;
    const handleBeforeUnload = event => event.preventDefault();
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, [preventDefault]);
}

If preventDefault is true, the window will not close. If it’s false, it will.

I use it in my App component, passing it a savedChanges prop:

function App({ savedChanges }) {
  usePreventWindowUnload(!savedChanges);
  // ...
}

I hope it helps you!