Skip to content

Instantly share code, notes, and snippets.

@n8jadams
Last active October 19, 2023 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8jadams/1ddd86274bf0786d5c0eae0ca36f701d to your computer and use it in GitHub Desktop.
Save n8jadams/1ddd86274bf0786d5c0eae0ca36f701d to your computer and use it in GitHub Desktop.
useBeforeClosingWindowPrompt - a hook that prompts user before they close the window when there are unsaved changes
import { useEffect } from "react";
/**
* A hook that prevents closing or refreshing if there are unsaved changes,
* offering the user a prompt to confirm before closing the window.
* @param promptBeforeClosingWindow A boolean indicating if we should prompt before closing
*/
export function useBeforeClosingWindowPrompt(promptBeforeClosingWindow: boolean) {
useEffect((): (() => void) => {
function handleBeforeUnload(e: BeforeUnloadEvent): void {
e.preventDefault();
// eslint-disable-next-line no-param-reassign
e.returnValue = ""; // Chrome requires returnValue to be set
}
if (promptBeforeClosingWindow) {
window.addEventListener("beforeunload", handleBeforeUnload);
}
return (): void => {
if (promptBeforeClosingWindow) {
window.removeEventListener("beforeunload", handleBeforeUnload);
}
};
}, [promptBeforeClosingWindow]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment