Shadcn Hooks

useUnmount

A hook to run a function when the component unmounts

Installation

npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-unmount.json"
pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-unmount.json"
yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-unmount.json"
bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-unmount.json"

Copy and paste the following code into your project.

use-latest.ts
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
}

use-unmount.ts
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): void

Credits

Last updated on