use-page-leave (use-page-leave)
Detects when the user tries to leave the page.
v0.1.0
Usage
import { use-page-leave } from "@/hooks"1"use client";
2
3import React, { useEffect } from "react";
4
5import { Badge } from "@/components/ui/badge";
6import { Button } from "@/components/ui/button";
7import {
8  Card,
9  CardContent,
10  CardDescription,
11  CardFooter,
12  CardHeader,
13  CardTitle,
14} from "@/components/ui/card";
15
16import { cn } from "@/lib/utils";
17
18import { usePageLeave } from "@/components/hooks/use-page-leave";
19
20export function UsePageLeaveDemo() {
21  const { isPageLeft, onPageLeave } = usePageLeave({
22    showConfirmation: true,
23    confirmationMessage:
24      "Are you sure you want to leave? Unsaved changes may be lost.",
25  });
26
27  useEffect(() => {
28    onPageLeave(() => {
29      // Custom action when the user leaves the page (tab switch)
30      // Example: save draft, send telemetry, etc.
31      // Replace this with whatever logic you need
32      // eslint-disable-next-line no-console
33      console.log("User left the page (tab switch)");
34    });
35  }, [onPageLeave]);
36
37  return (
38    <Card className="relative max-w-sm w-full">
39      <CardHeader>
40        <CardTitle>usePageLeave</CardTitle>
41        <CardDescription>
42          This component demonstrates the <code>usePageLeave</code> hook to
43          detect when the user switches tabs or tries to leave the page.
44        </CardDescription>
45      </CardHeader>
46      <CardContent className="space-y-4">
47        <Badge
48          variant="secondary"
49          className={cn(
50            "w-fit",
51            isPageLeft
52              ? "bg-yellow-500/30 border-yellow-500 text-yellow-700"
53              : "bg-green-500/30 border-green-500 text-green-700"
54          )}
55        >
56          {isPageLeft
57            ? "You left the page (tab in background)"
58            : "You are viewing this page"}
59        </Badge>
60        <p className="text-sm text-muted-foreground">
61          Open another tab or minimize the browser to see the status change.
62          <br />
63          Also try closing or reloading the page to see the confirmation alert.
64        </p>
65      </CardContent>
66      <CardFooter>
67        <Button
68          size="sm"
69          variant="outline"
70          onClick={() => window.location.reload()}
71        >
72          Reload page
73        </Button>
74      </CardFooter>
75    </Card>
76  );
77}
78Install
npx wkkkis-hooks add use-page-leaveOptions
| Name | Type | Default | Description | 
|---|---|---|---|
| confirmationMessage | string | - | Custom message to show in the browser's confirmation dialog. Note: Most modern browsers ignore custom messages for security reasons. | 
| showConfirmation | boolean | false | Whether to show the browser's confirmation dialog when the user tries to leave the page. | 
Features
- Tab Switch Detection : Uses the visibilitychange event to detect when the user switches tabs or minimizes the browser.
 - Page Close/Reload Detection : Uses the beforeunload event to detect when the user tries to close or reload the page.
 - Confirmation Dialog : Optionally shows a confirmation dialog when the user tries to leave the page.
 - Custom Callback : Allows you to execute custom logic when the user leaves the page.
 - SSR Safe : Checks for the window object before adding event listeners, making it safe to use in SSR/Next.js environments.
 
Files in this hook
| Source | Destination | 
|---|---|
| files/use-page-leave.ts | src/hooks/use-page-leave.ts |