Use Unmount

A hook that runs a cleanup function when the component is unmounted.

Installation

CLI

npx shadcn@latest add https://kelvinmai.io/r/use-unmount.json

Manual

Copy and paste the following code into your project

hooks/use-unmount.ts
import * as React from 'react';
export const useUnmount = (f: () => void) => {
const fRef = React.useRef(f);
fRef.current = f;
React.useEffect(
() => () => {
fRef.current();
},
[],
);
};

Update the import paths to match your project setup

Usage

import { useMount } from '@/hooks/use-unmount';
export default function Component() {
useUnmount(() => {
// Cleanup logic here
});
return <div>Hello world</div>;
}

API Reference

Parameters

NameTypeDescription
func
() => void
The cleanup function to be executed on unmount.

Returns

void