h3/use's logo

h3/use

Command Palette

Search for a command to run...

usePageLeave

Detects when the user tries to leave the page.

usePageLeave
This component demonstrates the usePageLeave hook to detect when the user switches tabs or tries to leave the page.
You are viewing this page

Open another tab or minimize the browser to see the status change.
Also try closing or reloading the page to see the confirmation alert.

Installation

Props

PropTypeDefaultDescription
confirmationMessagestring-Custom message to show in the browser's confirmation dialog. Note: Most modern browsers ignore custom messages for security reasons.
showConfirmationbooleanfalseWhether to show the browser's confirmation dialog when the user tries to leave the page.

Data

PropertyTypeDescription
isPageLeftbooleanIndicates whether the user has left the page (tab is in background or hidden).
onPageLeave(callback: () => void) => voidFunction to register a callback that will be executed when the user leaves the page.

Key Features & Details

  • Tab Switch Detection: Uses the visibilitychange event to detect when the user switches tabs or minimizes the browser.
  • Page Close/Reload Detection: Uses the beforeunload event to detect when the user tries to close or reload the page.
  • Confirmation Dialog: Optionally shows a confirmation dialog when the user tries to leave the page.
  • Custom Callback: Allows you to execute custom logic when the user leaves the page.
  • SSR Safe: Checks for the window object before adding event listeners, making it safe to use in SSR/Next.js environments.

Examples

Save Draft on Page Leave

function Editor() {
  const { onPageLeave } = usePageLeave({
    showConfirmation: true,
    confirmationMessage:
      'You have unsaved changes. Are you sure you want to leave?',
  });
 
  useEffect(() => {
    onPageLeave(() => {
      // Auto-save draft when user leaves
      saveDraft();
    });
  }, [onPageLeave]);
 
  return <div>Editor content</div>;
}

Track User Engagement

function Analytics() {
  const { isPageLeft, onPageLeave } = usePageLeave();
 
  useEffect(() => {
    onPageLeave(() => {
      // Send analytics when user leaves
      trackUserEngagement();
    });
  }, [onPageLeave]);
 
  return <div>User is {isPageLeft ? 'not' : ''} engaged with the page</div>;
}