use-on-unmount (use-on-unmount)
Execute a function only once when the component is unmounted.
v0.1.0
Usage
import { use-on-unmount } from "@/hooks"1"use client";
2
3import React, { useState } from "react";
4
5import { toast } from "sonner";
6
7import { Button } from "@/components/ui/button";
8import {
9  Card,
10  CardContent,
11  CardDescription,
12  CardFooter,
13  CardHeader,
14  CardTitle,
15} from "@/components/ui/card";
16
17import { useOnUnmount } from "@/components/hooks/use-on-unmount";
18
19function ChildComponent() {
20  useOnUnmount(() => {
21    toast.success("Component unmounted successfully!");
22  });
23
24  return (
25    <div className="p-4 rounded-md bg-muted">
26      <p>I am the child component. Click to unmount me!</p>
27    </div>
28  );
29}
30
31export function UseOnUnmountDemo() {
32  const [showChild, setShowChild] = useState(true);
33
34  return (
35    <Card className="relative max-w-md w-full">
36      <CardHeader>
37        <CardTitle>useOnUnmount</CardTitle>
38        <CardDescription>
39          This example uses the <code>useOnMount</code> hook to execute a
40          function only once when the component is mounted.
41        </CardDescription>
42      </CardHeader>
43      <CardContent>
44        <Button onClick={() => setShowChild((prev) => !prev)}>
45          {showChild ? "Unmount child component" : "Mount child component"}
46        </Button>
47        <div className="mt-6 min-h-[60px]">
48          {showChild && <ChildComponent />}
49        </div>
50      </CardContent>
51      <CardFooter>
52        <p className="text-muted-foreground text-sm">
53          When the child component is unmounted, a toast will be displayed using
54          shadcn/ui.
55        </p>
56      </CardFooter>
57    </Card>
58  );
59}
60Install
npx wkkkis-hooks add use-on-unmountOptions
| Name | Type | Default | Description | 
|---|---|---|---|
| callback | void function | () => {} | The function to execute when the component is unmounted. | 
Execution Timing
- The callback is executed only once, immediately before the component is unmounted (on the client).
 - The callback will not run on re-renders or updates, only on unmount.
 
Callback Stability
- The callback is not re-invoked if it changes between renders; only the initial callback is used.
 - For best results, use a stable callback (e.g., from useCallback ) if it depends on props or state.
 
SSR & Client-Only
- The hook is client-side only; on the server, the callback is never called.
 
Best Practices & Caveats
- Use for cleanup logic, analytics, or side effects that should only run once on unmount.
 - Avoid side effects that depend on up-to-date props or state unless the callback is stable.
 
Files in this hook
| Source | Destination | 
|---|---|
| files/use-on-unmount.ts | src/hooks/use-on-unmount.ts |