Effects

useUnmount

Runs a cleanup function once, when the component unmounts.

Demo

mounted — cleanup armed
status
mounted
cleanups run
0

Usage

use-unmount.tsxtsx
import { useUnmount } from "hookli";

export function Demo() {
  useUnmount(() => {
    console.log("cleanup on unmount");
  });

  return <p>Watch the console when I unmount.</p>;
}

API

useUnmount.d.tsts
useUnmount(fn: () => void): void

Parameters

NameTypeDefaultDescription
fn() => voidCalled exactly once when the component unmounts. The latest closure is captured in a ref, so it always sees fresh values.

Returns

This hook returns nothing.

Hook

The implementation, straight from hookli. Copy it, or install the package.

src/hooks/use-unmount/use-unmount.tstsx
import { useEffect, useRef } from "react";

export const useUnmount = (fn: () => void) => {
  const fnRef = useRef(fn);

  // The latest closure every render, but only invoked on unmount.
  fnRef.current = fn;

  useEffect(() => () => fnRef.current(), []);
};

View source on GitHub

Related hooks