useLeavePage
A custom React hook that detects when the user is leaving the page by monitoring the mouseleave event.
useLeavePage
is a custom React hook that detects when a user is about to leave the page by monitoring when their mouse cursor leaves the browser window. This is commonly used for implementing exit-intent popups, auto-saving content, or showing retention messages to keep users engaged.
Loading...
Install
npx shadcn@latest add https://unlogg.com/r/use-leave-page.json
pnpm dlx shadcn@latest add https://unlogg.com/r/use-leave-page.json
bunx shadcn@latest add https://unlogg.com/r/use-leave-page.json
Notes
- Monitors the "mouseleave" event on the document by default
- Detects when the cursor leaves the browser window area
- Automatically resets when the cursor returns to the page
- Client-side only (safe for SSR applications)
- Useful for exit-intent functionality and user retention
API Reference
Parameters
This hook takes no parameters.
Returns
Prop | Type | Default |
---|---|---|
isLeavingPage? | boolean | - |
Usage
import { useLeavePage } from "@/hooks/use-leave-page";
function ExitIntentPopup() {
const isLeavingPage = useLeavePage();
if (isLeavingPage) {
return (
<div className="popup">
<h2>Wait! Don't leave yet!</h2>
<p>You have unsaved changes.</p>
</div>
);
}
return <div>Page content</div>;
}
Examples
Exit intent popup
Loading...
Auto save content on leave
Loading...
Use Cases
- Exit Intent Popups: Show special offers or newsletters when users are about to leave
- Auto-Save Functionality: Automatically save user content when they move away
- Cart Abandonment Prevention: Remind users about items in their shopping cart
- Form Data Protection: Warn users about unsaved form changes
- Analytics Tracking: Track user exit behavior for optimization
- Retention Messages: Show engaging content to keep users on the page
- Session Management: Trigger session-related actions before users leave
- Content Protection: Save drafts or warn about unsaved work