Skip to content

useUnmount

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

Usage

tsx
import { useUnmount } from 'vhooks'

export default function Component() {
  useUnmount(() => {
    // Cleanup logic here
  })

  return <div>Hello world</div>
}

Installation

sh
pnpm dlx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useUnmount.json -e %src%/hooks
sh
npx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useUnmount.json -e %src%/hooks
sh
bunx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useUnmount.json -e %src%/hooks
sh
yarn dlx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useUnmount.json -e %src%/hooks

API

useUnmount(func): void

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

Parameters

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

Returns

void

Hook

ts
import { useEffect, useRef } from 'react'

export function useUnmount(func: () => void) {
  const funcRef = useRef(func)

  funcRef.current = func

  useEffect(
    () => () => {
      funcRef.current()
    },
    [],
  )
}

vDocs