How to Use onDestroy in Svelte: Cleanup Lifecycle Explained
In Svelte, use the
onDestroy function to run cleanup code when a component is removed from the page. Import onDestroy from 'svelte' and pass it a callback that runs your cleanup logic.Syntax
The onDestroy function is imported from 'svelte' and accepts a callback function. This callback runs when the component is about to be removed from the DOM, letting you clean up resources like timers or event listeners.
Example parts:
import { onDestroy } from 'svelte';- imports the functiononDestroy(() => { ... })- registers cleanup code
svelte
import { onDestroy } from 'svelte'; onDestroy(() => { // cleanup code here });
Example
This example shows a timer that logs a message every second. When the component is removed, onDestroy clears the timer to stop it.
svelte
<script> import { onDestroy } from 'svelte'; const interval = setInterval(() => { console.log('Timer running'); }, 1000); onDestroy(() => { clearInterval(interval); console.log('Timer stopped on destroy'); }); </script> <p>Open the console to see the timer messages. When the component unmounts, the timer stops.</p>
Output
Timer running (every second)
... (repeats)
Timer stopped on destroy (once when component unmounts)
Common Pitfalls
Common mistakes when using onDestroy include:
- Not clearing timers or unsubscribing from events, causing memory leaks.
- Trying to use
onDestroyoutside component script context. - Forgetting to import
onDestroyfrom 'svelte'.
Always pair resource setup with cleanup inside onDestroy.
svelte
<!-- Wrong: forgetting to clear timer --> <script> const interval = setInterval(() => { console.log('Timer running'); }, 1000); </script> <!-- Right: clear timer on destroy --> <script> import { onDestroy } from 'svelte'; const interval = setInterval(() => { console.log('Timer running'); }, 1000); onDestroy(() => { clearInterval(interval); }); </script>
Quick Reference
onDestroy Cheat Sheet:
- Import with
import { onDestroy } from 'svelte'; - Pass a callback to run cleanup code
- Use to clear timers, unsubscribe events, or cancel async tasks
- Runs once when component is removed
Key Takeaways
Use onDestroy to run cleanup code when a Svelte component is removed.
Always import onDestroy from 'svelte' before using it.
Clear timers and unsubscribe events inside onDestroy to avoid memory leaks.
The onDestroy callback runs once when the component unmounts.
Do not use onDestroy outside the component script context.