Skip to main content

All hooks

useUnmount

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


Parameters

  • func: The cleanup function to be executed on unmount.

Usage

import { useUnmount } from './useUnmount'

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

  return <div>Hello world</div>
}

API

function useUnmount(func: () => void): void

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

Parameters

NameTypeDefault valueDescription
func() => void-The cleanup function to be executed on unmount.

Returns

No return description available yet.

Hook

import { useEffect, useRef } from 'react'

import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect'

/**
 * Custom hook that runs a cleanup function when the component is unmounted.
 * @param {() => void} func - The cleanup function to be executed on unmount.
 * @public
 * @see [Documentation](https://usehooks-ts.com/react-hook/use-unmount)
 * @example
 * ```tsx
 * useUnmount(() => {
 *   // Cleanup logic here
 * });
 * ```
 */
export function useUnmount(func: () => void) {
  const funcRef = useRef(func)

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

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