useBeforeUnload
A hook for easily handling the beforeunload event in React.
The beforeunload event fires when the user is about to leave the page.
The primary use case for the beforeunload event is to display a confirmation dialog asking the user whether they really want to leave the page.
If the user clicks the confirm button, the browser navigates to the new page; otherwise, navigation is cancelled and the user stays on the current page.
Code
Interface
typescript
function useBeforeUnload(enabled?: boolean | (() => boolean) = true): void
Parameters
| Name | Type | Description |
|---|---|---|
enabled | boolean | (() => boolean) | Whether to activate the hook. When false, the event listener is not registered. Defaults to true |
Usage
typescript
import { useBeforeUnload } from '@modern-kit/react'
const Example = () => {
useBeforeUnload();
return <div>Try leaving the page.</div>;
};
Example
Try leaving the page.