Svelte 18: Lifecycle — onMount & onDestroy
easy⏱ 5 mincoursesvelte
onMount: runs once, after the component is in the DOM
onMount fires after Svelte has mounted the component's elements — safe to measure DOM nodes, start timers, or kick off a data fetch. If the function you pass to onMount itself returns a function, Svelte treats that returned function as the onDestroy handler automatically — a shorthand for the mount+unmount pair when they're closely related.
<script>
import { onMount } from 'svelte';
onMount(() => {
console.log('mounted!');
// optional: return a cleanup, same as onDestroy
return () => console.log('unmounting via onMount return');
});
</script>
onDestroy: guaranteed teardown
onDestroy runs exactly once, when the component is removed from the tree — whether that's because the user navigated away, an {#if} block toggled off, or an {#each} item was removed. It's the right place for anything onMount started that needs explicit teardown: clearInterval, closing a WebSocket, unsubscribing from a store.
<script>
import { onMount, onDestroy } from 'svelte';
let id;
onMount(() => { id = setInterval(() => console.log('tick'), 1000); });
onDestroy(() => clearInterval(id));
</script>
onMount/onDestroy vs $effect — when to use which
If your logic depends on REACTIVE VALUES and should re-run whenever they change, use $effect. If it's a true one-time setup/teardown pair that has nothing to do with reactive dependencies — like registering a global keyboard shortcut for the component's lifetime — onMount/onDestroy communicates that intent more clearly, even though a dependency-free $effect could technically do the same job.