useBeforeUnload

Tags:

A React Hook to perform actions before the page is unloaded (e.g., closing, refreshing the page) and optionally trigger a browser-native confirmation dialog. set preventDefault to true to show the confirm leave dialog.

Demo

Try to close/refresh this page with different status and see what happens!

Source
Show confirm dialog:
true

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

useBeforeUnload(callback, options)

Callback

A function that will be called right before the page is potentially unloaded.

/** * A callback function to run before the page is unloaded * * @param {BeforeUnloadEvent} event - `BeforeUnloadEvent`, the event object * @returns {void} `void` */ export type UseBeforeUnloadCallback = (event: BeforeUnloadEvent) => void

Options

export interface UseBeforeUnloadOptions { /** * Whether to prevent the default behavior of the event, which leads to showing a browser-native message * * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event * * @defaultValue false */ preventDefault?: boolean }

Returns

A clear function to remove the event listener.