0Pricing
Sveltejs Academy · Lesson

The destroy() Cleanup Function

Return a destroy function from an action to clean up event listeners and observers.

Why Cleanup

Actions often add listeners or observers. Cleanup prevents memory leaks when the element unmounts.

Return destroy

An action can return an object with a destroy() function. Svelte calls it on unmount.

function listen(node) {
  function onClick() { /* ... */ }
  node.addEventListener("click", onClick);
  return { destroy() { node.removeEventListener("click", onClick); } };
}

All lessons in this course

  1. use: Directive Syntax
  2. Action Parameters and Updates
  3. The destroy() Cleanup Function
  4. Practical Actions: clickOutside tooltip autofocus
← Back to Sveltejs Academy