What if your app could clean up after itself perfectly every time you leave a page?
Why onDestroy in Svelte? - Purpose & Use Cases
Imagine you create a popup or a timer in your app, and when you close or leave that part, you forget to stop the timer or remove the popup.
Without cleaning up, timers keep running, event listeners stay active, and memory fills up. This makes your app slow and buggy over time.
The onDestroy function in Svelte lets you run cleanup code automatically when a component is removed, keeping your app fast and error-free.
const timer = setInterval(() => { console.log('tick'); }); // but no clearInterval when doneimport { onDestroy } from 'svelte'; const timer = setInterval(() => { console.log('tick'); }, 1000); onDestroy(() => clearInterval(timer));
You can safely create temporary effects or listeners that clean themselves up, making your app smooth and reliable.
When showing a live chat widget, onDestroy stops the message polling when the chat closes, saving resources.
onDestroy runs cleanup code when a component is removed.
It prevents memory leaks and unwanted background tasks.
Using it keeps your app fast and bug-free.