Skip to content

useBeforeUnload

Hook to handle beforeunload event.

Demo

INFO

The component uses useBeforeUnload hook to ask confirm to user if he is sure to leave page when he changes page.

Loading demo…
Show source code
tsx
import { useCallback } from "react";
import { useBeforeUnload } from "../../../.."

export const UseBeforeUnload = () => {
	useBeforeUnload({
		listener: useCallback((evt: BeforeUnloadEvent) => {
			evt.preventDefault();
			evt.returnValue = "";
		}, [])
	});

	return (<>
		<a href="https://www.google.it">Go to google</a>
	</>);
}

Types

UseBeforeUnloadProps

Parameters accepted by useBeforeUnload.

PropertyTypeRequiredDescription
elementRefObject<HTMLElement> \| WindowThe target on which the beforeunload event listener is registered. Accepts either a React RefObject&lt;HTMLElement&gt; or a direct Window reference. When omitted, the listener is attached to the global window object.
listener(evt: BeforeUnloadEvent) => voidThe event handler invoked when the beforeunload event fires. Receives the native {@link BeforeUnloadEvent}. To trigger the browser's built-in leave confirmation dialog, call evt.preventDefault() inside this handler (the returnValue approach is deprecated in modern browsers).
optsboolean \| AddEventListenerOptionsOptions forwarded to addEventListener as the third argument. Accepts either a boolean shorthand for capture or a full {@link AddEventListenerOptions} object. When omitted, the listener is registered with the browser defaults (bubble phase, non-passive, non-once).

UseBeforeUnloadResult

Return value of useBeforeUnload.

A stable cleanup function that manually removes the beforeunload listener from the target element. Calling it is optional — the hook removes the listener automatically on unmount — but it can be useful to detach the listener earlier in response to a user action (e.g. after a successful save that makes the warning unnecessary).

ts
export type UseBeforeUnloadResult = () => void;

Released under the MIT License.