VayuUI

usePageLeave

A hook that runs a callback when the user's mouse leaves the page.

The usePageLeave hook triggers a callback function when the user's cursor leaves the document, typically moving towards the browser tab bar. This is useful for showing exit-intent popups or saving state before the user leaves.

Demo

Move your mouse cursor out of the page (towards the top tab bar) to see the effect.

Source Code

Copy this code into src/hooks/usePageLeave.ts:

import { useEffect } from 'react';

export const usePageLeave = (callback: () => void) => {
  useEffect(() => {
    const handleMouseOut = (event: MouseEvent) => {
      if (!event.relatedTarget && event.clientY <= 0) {
        callback();
      }
    };

    document.addEventListener('mouseout', handleMouseOut);

    return () => {
      document.removeEventListener('mouseout', handleMouseOut);
    };
  }, [callback]);
};

Usage

import { usePageLeave } from '@/hooks/usePageLeave';

const ExitIntentPopup = () => {
  usePageLeave(() => {
    console.log('User is leaving the page!');
    // Show modal or perform action
  });

  return <div>Content</div>;
};

API Reference

Parameters

NameTypeDescription
callback() => voidThe function to execute when the mouse leaves the page.

On this page