Docs

Lifecycle & effects

Most lifecycle needs are covered by $effect; onMount is still there when you need run-once setup.

Run-once setup

onMount runs after the component is first added to the page — good for measuring the DOM or starting a subscription.

svelte
svelte
<script>
  import { onMount } from 'svelte';
  onMount(() => console.log('mounted'));
</script>

Cleanup

Return a function from $effect (or onMount) to clean up — Svelte calls it before the effect re-runs and when the component is destroyed.

svelte
svelte
<script>
  $effect(() => {
    const id = setInterval(() => console.log('tick'), 1000);
    return () => clearInterval(id);
  });
</script>

Rule of thumb