Svelte Lifecycle Events
By Flavio Copes
Learn how to run setup and cleanup code in Svelte 5 with onMount, onDestroy, effects, and tick.
A Svelte 5 component has two lifecycle moments: creation and destruction.
Use onMount for setup that needs the browser. Use onDestroy or an onMount cleanup function when the component goes away.
onMount
Import onMount from svelte:
<script>
import { onMount } from 'svelte'
onMount(() => {
console.log('The component is mounted')
})
</script>
onMount does not run when Svelte renders the component on the server.
A common use is starting a timer or connecting to a browser API.
Clean up work started on mount
Return a function from onMount to clean up:
<script>
import { onMount } from 'svelte'
onMount(() => {
const interval = setInterval(() => {
console.log('Checking')
}, 1000)
return () => {
clearInterval(interval)
}
})
</script>
Keep the onMount callback synchronous when returning cleanup code. An async function returns a promise, not a cleanup function.
onDestroy
Use onDestroy when cleanup is separate from the mount work:
<script>
import { onDestroy } from 'svelte'
onDestroy(() => {
console.log('The component is being destroyed')
})
</script>
Svelte calls it immediately before removing the component.
React to state updates
Svelte 5 does not treat every state change as a component-wide update. Use $effect to react to the state you care about:
<script>
let count = $state(0)
$effect(() => {
console.log(`The count is ${count}`)
})
</script>
The effect runs after Svelte updates the DOM.
Use $effect.pre when you must run code before the DOM update. Use tick() when you need to wait until pending changes are applied.
The old beforeUpdate and afterUpdate hooks are deprecated in Svelte 5. They only work in legacy components.
Related posts about svelte: