Docs
usePageLeave
Track when a user navigates away from a webpage with usePageLeave.
Loading...
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-page-leave
Usage
"use client"
import * as React from "react"
import { usePageLeave } from "@/hooks/use-page-leave"
export function Component() {
const elementRef = React.useRef<HTMLDivElement>(null)
const [distractions, setDistractions] = React.useState(0)
usePageLeave(() => {
setDistractions((d) => d + 1)
}, elementRef)
return (
<div ref={elementRef}>
<p>(Mouse out of the page)</p>
<h3>
You've been distracted {distractions}{" "}
{distractions === 1 ? "time" : "times"}.
</h3>
</div>
)
}
API Reference
Parameters
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
cb | Function | The callback function to be invoked when the user navigates away from page. | - | No |
ref | RefObject | The reference to the element to track the mouse out event. | document.documentElement | Yes |