Skip to content

listener-cleanup ​

Inside a function: addEventListener with a handler written in place (or passed by a name that nothing else reads) and no way to remove it, or setInterval whose id is thrown away.

Why: removing a listener needs the same function, and an inline one can't be named again; nor can one in a const (or a function declaration) whose only read is this call: nothing removes what nothing names. An interval needs its id. Such handlers stay registered for as long as the target lives, and keep everything they captured alive with them (v8.dev). Each call to the function adds another one.

✕ Rejectedlistener-cleanup
ts
export function trackResize(target: EventTarget, onResize: () => void): void {
  target.addEventListener("resize", () => onResize());
}

✅ Accepted: the caller decides when it ends

✓ Accepted0 diagnostics
ts
export function trackResize(target: EventTarget, onResize: () => void, signal: AbortSignal): void {
  target.addEventListener("resize", () => onResize(), { signal });
}

using sub = listen(target, "resize", handler) from @evobug_com/safe-ts-std/events counts too. Code at module level is not reported: it lives as long as the app.

{ once: true } on something that lives as long as the page ​

{ once: true } removes the listener when the event fires, and only then. On an object that goes away with the work (an element or a socket the function made) that is enough. On something that lives as long as the page or the program, it isn't: window, document, globalThis, self, navigator and anything under it, screen, visualViewport, a matchMedia(...) list (the same query gives back the same list), or a value made at module level. If the event never comes (the screen's resolution never changes, the page is already loaded), the handler stays registered, and keeps everything it captured alive. An adopter's tests kept the whole previous page alive on each boot this way, about 150 MB a boot, through a once listener on a matchMedia list. There it needs a signal too (or a removal).

✕ Rejectedlistener-cleanup
ts
export function watchResolution(onChange: () => void): void {
  matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`).addEventListener("change", () => onChange(), {
    once: true,
  });
}

✅ Accepted: the caller can end it

✓ Accepted0 diagnostics
ts
export function watchResolution(onChange: () => void, signal: AbortSignal): void {
  matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`).addEventListener("change", () => onChange(), {
    once: true,
    signal,
  });
}

A listener on an element the function makes itself (const b = document.createElement(...), createElementNS, new Image(), new Audio(), new Option(), new XElement()) isn't reported either: it lives exactly as long as the element, and goes away with it. The same goes for any object the function makes with new (const socket = new WebSocket(url)), as long as it adds the listener before it hands the object out (passes it to a function, stores or returns it): until then, nothing else can hold it.

✓ Accepted0 diagnostics
ts
export function connect(url: string, onText: (text: string) => void): WebSocket {
  const socket = new WebSocket(url);
  socket.addEventListener("message", (e) => onText(String(e.data)));
  return socket;
}
✓ Accepted0 diagnostics
ts
export function makeButton(label: string, onClick: () => void): HTMLButtonElement {
  const button = document.createElement("button");
  button.textContent = label;
  button.addEventListener("click", () => onClick());
  return button;
}

In Vue components ​

A component lives for less time than the app, so in Vue more is reported: anything a component starts during setup (in <script setup>, in a composable's body, or in onMounted and the other lifecycle hooks) and never stops. That includes a listener added with a named function, setInterval even when its id is kept, and a ResizeObserver, IntersectionObserver, MutationObserver or PerformanceObserver. Each keeps running after the component is gone, and every remount adds another. Guide: Vue.

✕ Rejectedlistener-cleanup
vue
<script setup lang="ts">
import { onMounted, ref } from "vue";

const online = ref(true);

function update(): void {
  online.value = navigator.onLine;
}

onMounted(() => {
  window.addEventListener("online", update);
  window.addEventListener("offline", update);
});
</script>

<template>
  <p>{{ online ? "Online" : "Offline" }}</p>
</template>

✅ Accepted: stopped when the component unmounts

✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { ref } from "vue";
import { useListener } from "@evobug_com/safe-ts-vue/listen";

const online = ref(navigator.onLine);

function update(): void {
  online.value = navigator.onLine;
}

useListener(window, "online", update);
useListener(window, "offline", update);
</script>

<template>
  <p>{{ online ? "Online" : "Offline" }}</p>
</template>

useListener(target, type, handler) and useInterval(fn, ms) from @evobug_com/safe-ts-vue/listen stop when the component's scope ends. Doing it by hand also counts: removeEventListener, clearInterval or observer.disconnect() in onScopeDispose, or { signal } from an AbortController you abort there. { once: true } counts too, except on a target that lives as long as the page (above).

Don't use using sub = listen(...) in <script setup>: using removes the listener when its block ends, and the block of <script setup> ends as soon as setup returns, before the component is shown. The rule reports using there (and in onMounted).

In React effects ​

An effect (useEffect, useLayoutEffect, useInsertionEffect) that adds a listener with a named function, starts an interval (even when its id is kept) or creates an observer, and returns no cleanup, is reported too. React runs the effect again when its dependencies change, and in development StrictMode runs it twice on mount, so each run adds another. Guide: React.

✕ Rejectedlistener-cleanup
tsx
import { useEffect, useState } from "react";

export function Online() {
  const [online, setOnline] = useState(true);
  useEffect(() => {
    const update = (): void => setOnline(navigator.onLine);
    window.addEventListener("online", update);
    window.addEventListener("offline", update);
  }, []);
  return <p>{online ? "Online" : "Offline"}</p>;
}

✅ Accepted: the effect returns what removes them

✓ Accepted0 diagnostics
tsx
import { useEffect, useState } from "react";

export function Online() {
  const [online, setOnline] = useState(true);
  useEffect(() => {
    const update = (): void => setOnline(navigator.onLine);
    window.addEventListener("online", update);
    window.addEventListener("offline", update);
    return () => {
      window.removeEventListener("online", update);
      window.removeEventListener("offline", update);
    };
  }, []);
  return <p>{online ? "Online" : "Offline"}</p>;
}

An interval id, a timeout or an AbortController that is kept, but not released on every way out of the function (an early return, an await that rejects), is unreleased-resource's: this rule reports a listener that can't be removed and an id thrown away.

What the rule can't see: a handler whose name is read twice is taken as removable, even if neither read removes it (el.addEventListener("x", onX); other.addEventListener("x", onX)), and a handler passed by name from another function or inside a loop; a long-lived target behind a parameter (target: EventTarget may be window: there { once: true } is taken as enough), or a module-level value imported under another name and stored in a local first. In a Vue component, it accepts any removeEventListener(, clearInterval( or .disconnect( anywhere in the file as the cleanup, without checking that it removes this listener. In a React effect, any returned function counts as the cleanup.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra