Skip to content

Cleanup ​

Window/document listeners, intervals, and observers registered inside a component keep running after unmount—leaking memory and stacking duplicate callbacks on every remount.

In short

  • Use scoped helpers: useListener and useInterval from @evobug_com/safe-ts-vue/listen tear down automatically on unmount.
  • Enforced statically: listener-cleanup flags listeners and intervals that have no matching cleanup.

Unremoved listeners and intervals outlive the component (listener-cleanup):

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

const width = ref(0);

function measure(): void {
  width.value = window.innerWidth;
}

onMounted(() => {
  window.addEventListener("resize", measure);
  setInterval(measure, 1000);
});
</script>

<template>
  <p>{{ width }}px</p>
</template>

useListener and useInterval from @evobug_com/safe-ts-vue/listen stop when the component unmounts:

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

const width = ref(window.innerWidth);

function measure(): void {
  width.value = window.innerWidth;
}

useListener(window, "resize", measure);
useInterval(measure, 1000);
</script>

<template>
  <p>{{ width }}px</p>
</template>

For an observer (a ResizeObserver for an element's size, say), call disconnect() in onScopeDispose. For events on elements in your own template, use @keydown, @scroll and friends there: Vue removes those itself.

Outside Vue, using sub = listen(...) from @evobug_com/safe-ts-std/events is how you remove a listener (std helpers). In <script setup> it is wrong: using removes the listener when its block ends, and the block of <script setup> ends as soon as setup returns, before the component is even shown. listener-cleanup reports it:

ts
// In <script setup>: removed straight away, before the component is shown.
using resize = listen(window, "resize", measure);

// Removed when the component unmounts.
useListener(window, "resize", measure);

Rules on this page: listener-cleanup

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