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
- use: Directive Syntax
- Action Parameters and Updates
- The destroy() Cleanup Function
- Practical Actions: clickOutside tooltip autofocus