Skip to main content

All hooks

usePageLeave

Custom hook that invokes a callback when the user's mouse leaves the page.


Pass a callback function that fires when the cursor exits the document. Useful for triggering exit-intent popups, save prompts, or analytics events.

Listens for the mouseout event on the document and checks if the cursor has left the viewport.

Usage

import { usePageLeave } from '@ts-hooks-kit/core'

function Example() {
  const result = usePageLeave()
  return <pre>{JSON.stringify(result, null, 2)}</pre>
}

API

function usePageLeave(handler: () => void): void

Custom hook that invokes a callback when the user's mouse leaves the page.

Parameters

NameTypeDefault valueDescription
handler() => void-The callback function to invoke when the mouse leaves the page.

Returns

No return description available yet.

Hook

import { useEffect } from 'react'

/**
 * Custom hook that invokes a callback when the user's mouse leaves the page.
 * @param {() => void} handler - The callback function to invoke when the mouse leaves the page.
 * @public
 * @see [Documentation](https://usehooks-ts.com/react-hook/use-page-leave)
 * @example
 * ```tsx
 * usePageLeave(() => {
 *   console.log('User is leaving the page');
 *   // Show "Don't leave!" modal or save draft
 * });
 * ```
 */
export function usePageLeave(handler: () => void): void {
  useEffect(() => {
    if (!handler) return

    const handleMouseLeave = () => {
      handler()
    }

    document.addEventListener('mouseleave', handleMouseLeave)

    return () => {
      document.removeEventListener('mouseleave', handleMouseLeave)
    }
  }, [handler])
}