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

cleanups

v0.0.1

Published

Simple, yet powerful utility for managing cleanups.

Readme

cleanups

Simple, yet powerful utility for managing cleanups.

This utility is widely used in screen.studio app and I believe it saved us a lot of time and effort.

TLDR:

import { createCleanup } from 'cleanups';

const cleanup = createCleanup();

cleanup.next = () => {
  console.log('cleanup 1');
};

cleanup.next = () => {
  console.log('cleanup 2');
};

cleanup.next = () => {
  console.log('cleanup 3');
};

cleanup();

// Output:
// cleanup 1
// cleanup 2
// cleanup 3

Note: I considered using cleanup.add(cb) instead of cleanup.next = cb, but decided to go with the latter as it results in less nesting (especially when using code formatters).

Rationale

I think there are two main problems with managing cleanups in JavaScript:

  1. JavaScript APIs are inconsistent in how they require you to clean up things
  2. It is hard to compose cleanups

Let's consider adding some event listeners and cleaning them up later.

// We need to store those functions to be able to remove them later
function someEventHandlerA() {}
function someEventHandlerB() {}

element.addEventListener('click', someEventHandlerA);
element.addEventListener('click', someEventHandlerB);

// Later on
return () => {
  element.removeEventListener('click', someEventHandlerA);
  element.removeEventListener('click', someEventHandlerB);
};

We need to call a different function to add and remove event listeners. We also need to store those functions in the outer scope.

The same goes with many other APIs:

  • setTimeout returns ID that you need to pass to clearTimeout
  • ResizeObserver.observe returns nothing and you need to call disconnect later
  • The same with requestAnimationFrame, IntersectionObserver, etc.

Now, let's create an improved version of addEventListener that simply returns a cleanup function and owns the responsibility of executing some cleanup logic.

function addEventListener<K extends keyof HTMLElementEventMap>(
  element: HTMLElement,
  type: K,
  handler: (event: HTMLElementEventMap[K]) => void,
  options?: boolean | AddEventListenerOptions,
) {
  element.addEventListener(type, handler, options);

  return () => element.removeEventListener(type, handler, options);
}

Now - the same code looks like this:

// We only need to know how to add event listeners, we don't need to remember how to remove them
const cleanup1 = addEventListener(element, 'click', function someEventHandlerA() {});
const cleanup2 = addEventListener(element, 'click', function someEventHandlerB() {});

// Later on
return () => {
  cleanup1();
  cleanup2();
};

We've already saved a bit. We also don't need to store those callbacks in the outer scope.

We can easily create similar wrappers like createTimeout, createAnimationFrame, etc.

function createTimeout(cb: () => void, delay: number) {
  const id = setTimeout(cb, delay);

  return () => clearTimeout(id);
}

Ok, now let's say we have some logic that is conditional and we have an array of elements we want to add event listeners to.

const elements = [element1, element2, element3];

const cleanups: Array<() => void> = [];

for (const element of elements) {
  if (someCondition) {
    cleanups.push(addEventListener(element, 'click', function someEventHandler() {}));
  }
}

// Later on
return () => {
  for (const cleanup of cleanups) {
    try {
      cleanup();
    } catch (e) {
      // We have to catch as otherwise one error would prevent cleaning up the rest
      console.error('Error while cleaning up', e);
    }
  }
};

It's already way better than if using .addEventListener and .removeEventListener directly, but it's still a bit messy.

Now let's use 'cleanups' utility:

import { createCleanup } from 'cleanups';

const cleanup = createCleanup();

const elements = [element1, element2, element3];

for (const element of elements) {
  if (someCondition) {
    cleanup.next = addEventListener(element, 'click', function someEventHandler() {});
  }
}

// Later on
cleanup();

Now, this is also composable:

Say we have a parent and a child class. We want to clean up both parent and all the children when the parent is destroyed.

class ParentThing {
  // Parent has its own cleanup. Children will add their cleanups to this cleanup
  destroy = createCleanup();

  constructor() {
    // Parent own cleanups
    this.destroy.next = () => {
      console.log('destroying parent');
    };

    this.destroy.next = addEventListener(this.foo, 'click', function someEventHandler() {});
  }

  children: ChildThing[] = [];

  addChild() {
    this.children.push(new ChildThing(this));
  }
}

class ChildThing {
  // Child has its own cleanup
  destroy = createCleanup();

  constructor(parent: ParentThing) {
    // Child has its own cleanups
    this.destroy.next = () => {
      console.log('destroying child');
    };

    // If parent is destroyed, child will be destroyed as well
    this.parent.destroy.next = this.destroy;
  }
}

API

createCleanup

function createCleanup(options?: CleanupOptions): CleanupObject;

interface CleanupOptions {
  // If true, the cleanup will be executed only once and will warn if more cleanups are added after it was executed
  once?: boolean;
  // This arg will be passed as `this` to each cleanup function
  thisArg?: unknown;
}

const cleanup = createCleanup();

cleanup.next = someFunction; // Add a cleanup to the cleanup chain
cleanup.wasCalled; // Returns true if the cleanup was already called at least once
cleanup(); // Execute all cleanups and reset the cleanup