useUnmount
A hook to run a function when the component unmounts
Installation
npx shadcn@latest add @hooks/use-unmountpnpm dlx shadcn@latest add @hooks/use-unmountyarn dlx shadcn@latest add @hooks/use-unmountbun x shadcn@latest add @hooks/use-unmountCopy and paste the following code into your project.
import { useRef } from 'react'
import { useIsomorphicLayoutEffect } from '@/registry/hooks/use-isomorphic-layout-effect'
export function useLatest<T>(value: T) {
const ref = useRef(value)
useIsomorphicLayoutEffect(() => {
ref.current = value
})
return ref
}import { useEffect } from 'react'
import { useLatest } from '@/registry/hooks/use-latest'
export function useUnmount(fn: () => void) {
const fnRef = useLatest(fn)
useEffect(
() => () => {
fnRef.current()
},
[],
)
}API
/**
* A hook to run a function when the component unmounts
* @param fn - The function to run when the component unmounts
* @returns The function to run when the component unmounts
*/
export function useUnmount(fn: () => void): voidCredits
Last updated on