OnMount vs onDestroy in Svelte: Key Differences and Usage
onMount runs code when a Svelte component first appears on the page, perfect for setup tasks. onDestroy runs code just before the component is removed, ideal for cleanup like removing event listeners or timers.Quick Comparison
Here is a quick side-by-side comparison of onMount and onDestroy in Svelte.
| Aspect | onMount | onDestroy |
|---|---|---|
| When it runs | After component is added to the DOM | Just before component is removed from the DOM |
| Purpose | Initialize or start tasks | Cleanup or stop tasks |
| Common uses | Fetching data, starting timers | Clearing timers, removing event listeners |
| Runs once? | Yes, once per component mount | Yes, once per component destroy |
| Return value | Can return a cleanup function | No return value expected |
Key Differences
onMount is a lifecycle function that runs after the component is inserted into the DOM. It is mainly used to start processes like fetching data, setting up subscriptions, or starting timers. It runs only once per component instance when it appears.
In contrast, onDestroy runs just before the component is removed from the DOM. It is used to clean up resources such as clearing timers, unsubscribing from stores, or removing event listeners to avoid memory leaks. It also runs once per component instance when it is about to disappear.
While onMount can optionally return a cleanup function that Svelte will call automatically on destroy, onDestroy is explicitly for cleanup tasks and does not expect a return value.
Code Comparison
import { onMount } from 'svelte'; let time = 0; let interval; onMount(() => { interval = setInterval(() => { time += 1; console.log('Timer:', time); }, 1000); // Optional cleanup function returned return () => { clearInterval(interval); console.log('Timer cleared on destroy'); }; });
onDestroy Equivalent
import { onDestroy } from 'svelte'; let time = 0; let interval = setInterval(() => { time += 1; console.log('Timer:', time); }, 1000); onDestroy(() => { clearInterval(interval); console.log('Timer cleared on destroy'); });
When to Use Which
Choose onMount when you need to run code right after your component appears, such as fetching data or starting timers. Use it if you want to return a cleanup function directly from the setup.
Choose onDestroy when you want to explicitly clean up resources before the component disappears, like clearing intervals or unsubscribing from events. It is best for cleanup tasks that must run reliably on component removal.
Key Takeaways
onMount runs once after the component is added to the page for setup tasks.onDestroy runs once before the component is removed for cleanup tasks.onMount can return a cleanup function; onDestroy is only for cleanup.onMount to start processes and onDestroy to stop or clean them.