If unsaved changes are there in the form, we will use the following code to show default alert message when user tries to reload or close the window or close the tab.
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (isFormChanged) {
e.preventDefault();
e.returnValue = '';
return '';
}
return undefined;
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [isFormChanged]);