npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@usefy/use-unmount

v0.2.5

Published

A React hook that executes a callback when the component unmounts

Readme

@usefy/use-unmount

A React hook that executes a callback when the component unmounts.

Features

  • Closure Freshness: Callback always has access to the latest state/props values
  • Error Handling: Errors in callback are caught and don't break unmount
  • Conditional Execution: Enable/disable cleanup via enabled option
  • SSR Compatible: Works safely with server-side rendering
  • TypeScript Support: Full type definitions included
  • Zero Dependencies: Only peer dependency on React

Installation

npm install @usefy/use-unmount
# or
pnpm add @usefy/use-unmount
# or
yarn add @usefy/use-unmount

Usage

Basic Usage

import { useUnmount } from "@usefy/use-unmount";

function MyComponent() {
  useUnmount(() => {
    console.log("Component unmounted");
  });

  return <div>Hello</div>;
}

With Latest State Access

import { useState } from "react";
import { useUnmount } from "@usefy/use-unmount";

function FormComponent() {
  const [formData, setFormData] = useState({});

  useUnmount(() => {
    // formData will have the latest value at unmount time
    saveToLocalStorage(formData);
  });

  return <form>...</form>;
}

Conditional Cleanup

import { useUnmount } from "@usefy/use-unmount";

function TrackingComponent({ trackingEnabled }) {
  useUnmount(
    () => {
      sendAnalyticsEvent("component_unmounted");
    },
    { enabled: trackingEnabled }
  );

  return <div>Tracked content</div>;
}

Resource Cleanup

import { useEffect, useRef } from "react";
import { useUnmount } from "@usefy/use-unmount";

function WebSocketComponent() {
  const wsRef = useRef<WebSocket | null>(null);

  useEffect(() => {
    wsRef.current = new WebSocket("wss://example.com");
  }, []);

  useUnmount(() => {
    wsRef.current?.close();
  });

  return <div>Connected</div>;
}

API

useUnmount(callback, options?)

Parameters

| Name | Type | Description | | ---------- | ------------------- | ------------------------------------------- | | callback | () => void | Function to execute when component unmounts | | options | UseUnmountOptions | Optional configuration |

Options

| Name | Type | Default | Description | | --------- | --------- | ------- | -------------------------------------- | | enabled | boolean | true | Whether to execute callback on unmount |

React StrictMode

In development with React StrictMode, components are intentionally mounted, unmounted, and remounted to detect side effects. This means the unmount callback may be called multiple times during development. This is expected behavior.

Error Handling

If the callback throws an error, it will be caught and logged to the console. This prevents unmount errors from breaking the entire component tree unmount process.

When to Use

Use useUnmount when you need to:

  • Save data before component removal
  • Send analytics events on component exit
  • Clean up resources that aren't managed by useEffect
  • Log component lifecycle events
  • Perform final state snapshots

When NOT to Use

Consider using useEffect cleanup instead when:

  • Cleaning up subscriptions (use useEffect return function)
  • Removing event listeners (use useEventListener hook)
  • Canceling requests (use abort controllers in useEffect)

The key difference is that useUnmount guarantees access to the latest values, while useEffect cleanup captures values at effect creation time.

Testing

This package maintains comprehensive test coverage to ensure reliability and stability.

Test Coverage

📊 View Detailed Coverage Report (GitHub Pages)

Test Categories

  • Callback execution on unmount
  • No callback execution on mount
  • No callback execution on rerender
  • Callback accesses latest values at unmount time
  • Updated callback reference is used on unmount
  • Latest state values are captured in callback
  • Default enabled state (true)
  • Explicit enabled: true
  • Disabled when enabled: false
  • Dynamic enabled state changes
  • Multiple enabled toggles
  • Errors in callback are caught and logged
  • Unmount process continues despite callback errors
  • Non-Error objects thrown are handled
  • Independent instances work correctly
  • Multiple hooks in same component
  • Independent enabled states per instance
  • Rapid mount/unmount cycles
  • Undefined options handling
  • Empty options object
  • Null-ish enabled values
  • Effect doesn't re-run when callback reference changes
  • Async callbacks are executed on unmount
  • Async error handling behavior

License

MIT © mirunamu

This package is part of the usefy monorepo.