Back to Hooks

usePageLeave

usePageLeave.tsx

usePageLeave

INTERACTION

// Detect when the user's cursor leaves the page (exit-intent)

Quick Usage

const { hasLeft, triggerPageLeave } = usePageLeave({ onPageLeave: showModal });

Features

Exit Intent
Mouse Leave Detection
Visibility Tracking
Configurable Sensitivity

When to Use

Ideal for displaying exit-intent popups, feedback forms, discount offers, or tracking user engagement patterns.

Interactive Example

Page Leave Detection

Status: On Page
Visibility: Visible
Last Leave: Never

Try this:

• Move your mouse to the very top of the browser window and then outside

• Switch to another tab or minimize the browser

• Use Alt+Tab to switch to another application

Perfect for exit-intent popups and user engagement tracking!

Complete Example

import { usePageLeave } from '@usegrand/react-hokss';

function ExitIntentModal() {
  const { hasLeft, resetPageLeave, isVisible } = usePageLeave({
    onPageLeave: () => {
      setShowModal(true);
    },
    sensitivity: 10,
    trackMouseLeave: true,
    trackVisibilityChange: true
  });

  return (
    <div>
      <p>User status: {hasLeft ? 'Left' : 'On page'}</p>
      <p>Page visibility: {isVisible ? 'Visible' : 'Hidden'}</p>
      <button onClick={resetPageLeave}>Reset</button>
    </div>
  );
}

API Reference

Parameters

optionsPageLeaveOptions

Configuration options for page leave detection

options.onPageLeavefunction

Callback function executed when user leaves the page

options.sensitivitynumber

Sensitivity threshold in pixels from top (default: 10)

options.delaynumber

Delay before considering user left in ms (default: 0)

options.trackMouseLeaveboolean

Whether to track mouse leave events (default: true)

options.trackVisibilityChangeboolean

Whether to track visibility changes (default: true)

options.trackBeforeUnloadboolean

Whether to track beforeunload events (default: true)

Returns

PageLeaveResult

Object containing page leave state and controls

hasLeft

Boolean indicating if user has left the page

triggerPageLeave

Function to manually trigger page leave detection

resetPageLeave

Function to reset the page leave state

isVisible

Boolean indicating if page is currently visible

lastLeaveTime

Date of last page leave event