usePageLeaveui-interaction
usePageLeave
NewSSR SAFEDetects when the cursor leaves the viewport with exit-intent filtering and trigger frequency control.
$ pnpm dlx shadcn@latest add @byphongphan/use-page-leaveRequires
@byphongphan in components.jsonuse-page-leave.tsx
Loading preview...
Installation
$ pnpm dlx shadcn@latest add @byphongphan/use-page-leaveRequires
@byphongphan in components.jsonUsage
Exit-Intent Retention Dialog
Unsaved Draft Reminder
Features
- Exit-Intent Heuristic: Measures
clientY <= 0to accurately capture intent when visitors aim for the browser's tab strip, address bar, or close button. - Boundary Filtering: Toggle between top-edge only (
onlyTop: true) for exit-intent or any viewport edge (onlyTop: false) for general canvas applications. - Trigger Frequency Control: Supports
once: trueto prevent repetitive dialogs or notifications during a user's session. - Ref-Stabilized Handlers: Stores the
onLeavecallback in an internal ref so changes to the callback never trigger unnecessary event listener re-attachments. - Root Element Delegation: Binds to
document.documentElementto cleanly avoid event bubbling quirks from nested child elements.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
onLeave | (() => void) | — | Optional callback invoked when the cursor exits the configured boundary. |
options.onlyTop | boolean | true | When true, triggers only when the mouse leaves through the top edge (clientY <= 0). |
options.once | boolean | false | When true, the onLeave callback will only be executed once during the component's life. |
Returns
boolean — Returns true if the cursor is currently outside the configured viewport boundary, or false when inside.