Svelte Lifecycle

The lifecycle is a component's life story, in this order: <script> runs, the first render (the component shows for the first time), onMount, an update every…

When is the right time to fetch the menu from the server: before the component shows, or after? And who stops the clock in the corner of the menu when the menu is closed? Both are a matter of the lifecycle, a component's life story: it is created, put on the page (mounted), updated, then removed (destroyed). Svelte gives you functions that run code at a given stage, above all onMount and onDestroy. If you come from React, together they fill the role of useEffect and its cleanup (a function that cleans up when the component is removed). From Vue, the names are nearly the same: onMounted and onUnmounted.

Picture Mrs. Sri opening her stall. First the rolling door goes up until the stall can be seen. Only then does she light the stove and phone the supplier for today's ingredients. That work, started once the stall is open, is onMount: code that runs after the component shows. At closing time, the stove is turned off before the door comes down. That's onDestroy: cleaning up before the component is removed. Forget it, and the gas keeps burning in a closed stall, like an interval that keeps running after its component is gone.

A component's order of life

This is what happens when App.svelte mounts <TodaysMenu />, the component whose code is in the next section:

Stage When it runs In TodaysMenu
<script> once, when the component is created menu starts as [], time is set
first render after the script <p>Loading menu...</p> enters the page
onMount once, after the first render the clock interval starts, fetchMenu() is called
update every time a $state changes the clock changes every second, the menu appears
onDestroy once, before the component is removed the interval is stopped

onMount: start work after it shows

This is TodaysMenu.svelte. The server is only pretend: fetchMenu() gives the menu after 800 ms (milliseconds).

<script>
  import { onMount, onDestroy } from "svelte"

  let menu = $state([])
  let time = $state(new Date().toLocaleTimeString("en-GB"))
  let timer

  function fetchMenu() {
    return new Promise((resolve) => {
      setTimeout(() => resolve(["Fried Rice", "Chicken Noodles", "Iced Tea"]), 800)
    })
  }

  onMount(async () => {
    timer = setInterval(() => {
      time = new Date().toLocaleTimeString("en-GB")
    }, 1000)
    menu = await fetchMenu()
  })

  onDestroy(() => {
    clearInterval(timer)
  })
</script>

<p>Time {time}</p>
{#if menu.length === 0}
  <p>Loading menu...</p>
{:else}
  <ul>
    {#each menu as name}
      <li>{name}</li>
    {/each}
  </ul>
{/if}
Time What shows
0 ms, first render Time 10:15:03, Loading menu...
800 ms Time 10:15:03, the list Fried Rice, Chicken Noodles, Iced Tea
1,000 ms Time 10:15:04, the same list

onDestroy: clean up before leaving

onDestroy(callback) runs once, just before the component is removed, for example when {#if show} in App becomes false. This is where you stop whatever you started earlier: clearInterval, removeEventListener, or unsubscribing from a store (a shared container for data, covered in the next lesson).

onMount may also return a function, and Svelte runs that function as a cleanup when the component is removed: onMount(() => { const t = setInterval(...); return () => clearInterval(t) }). But that only works for a callback that isn't async. An async callback always returns a Promise, not a function, so its cleanup is ignored. TodaysMenu's onMount is async (because it uses await), so its interval is stopped in onDestroy.

The interval nobody stopped

Without onDestroy, the component leaves the page, but its interval keeps running. Every time the menu is opened and then closed, one interval is left behind:

Event Component on the page Intervals running
Open TodaysMenu #1 1
Close (none) 1, with no owner
Open TodaysMenu #2 2
Close (none) 2, with no owner
Open TodaysMenu #3 3

So when the menu is opened for the third time, there are 3 intervals. Two of them keep changing variables of components that no longer exist. This is called a memory leak: work and memory that are never released. With onDestroy(() => clearInterval(timer)), the number of intervals is always 1 while the menu is open, and 0 while it is closed.

Exercise: a message after mount

In the exercise, message is made with $state("Loading...") and shown in <p>{message}</p>. The answer:

<script>
  import { onMount } from "svelte"

  let message = $state("Loading...")

  onMount(() => {
    message = "Component mounted!"
  })
</script>

<p>{message}</p>

The first render shows Loading..., then onMount changes message. Since message is $state, the paragraph becomes Component mounted! right away.

📌 $effect.pre, $effect and tick

Two runes run code around a DOM update (when Svelte changes the page), and neither needs an import. $effect.pre(fn) runs before the DOM is updated, and $effect(fn) runs after it. Both run for the first time when the component is mounted, then again whenever a $state they read changes. Just like onMount, they only run in the browser.

$effect can also replace the onMount and onDestroy pair for an interval. The function it returns runs as a cleanup when the component is removed:

<script>
  let time = $state(new Date().toLocaleTimeString("en-GB"))

  $effect(() => {
    const timer = setInterval(() => {
      time = new Date().toLocaleTimeString("en-GB")
    }, 1000)
    return () => clearInterval(timer)
  })
</script>

tick() gives a Promise that resolves after the next DOM update. For example, take let portions = $state(1) and a Portions: {portions} heading. Right after portions += 1, the heading on the page still reads Portions: 1. After await tick(), it reads Portions: 2. Use tick when your code needs to read the updated DOM.

Older code: beforeUpdate and afterUpdate

In Svelte 4 code, you'll meet two more lifecycle functions from "svelte": beforeUpdate (runs before the DOM is updated) and afterUpdate (runs after it). Today they map to $effect.pre and $effect. The difference: the old functions run every time the component updates, whatever changed. The runes only rerun when a value they read changes. In a component that uses runes, the compiler refuses both, with an error such as beforeUpdate cannot be used in runes mode. onMount, onDestroy and tick are written the same in older code.

⚠️ Leaking intervals and elements that don't exist yet

TL;DR: The lifecycle is a component's life story, in this order: <script> runs, the first render (the component shows for the first time), onMount, an update every time a $state changes, then onDestroy before the component is removed. onMount, onDestroy and tick are imported from "svelte". onMount runs once after the component shows, and only in the browser. So it's the place to fetch data (menu = await fetchMenu(), with menu from $state) and start intervals. onDestroy is the place to clean up, for example clearInterval(timer). Without it, every time the component is opened and then closed, one interval is left behind and keeps running. onMount may return a cleanup (a function that cleans up when the component is removed), but not when the function you give onMount is async. $effect.pre runs before the DOM updates, and $effect after. $effect can also start an interval and return its cleanup. tick() waits until the DOM has been updated. The exercise: let message = $state("Loading..."), then onMount(() => { message = "Component mounted!" }), so the <p> changes from Loading... to Component mounted!.

⚡ onMount: start work after it shows

Write:

<script>
  import { onMount } from "svelte"

  let message = $state("Loading...")

  onMount(() => {
    message = "Component mounted!"
  })
</script>

<p>{message}</p>
Guess first: the function inside onMount runs after the component first shows. What does the paragraph hold when the component first shows?

Loading.... The page doesn't wait for onMount: the function inside it only runs once, after the component first shows. Then the paragraph becomes Component mounted!.

Meaning: onMount is imported from "svelte". The function inside it runs once, after the component first shows, and only in the browser. So onMount is the place to fetch data and start intervals.

⚡ onDestroy: clean up before leaving

Write:

onDestroy(() => {
  clearInterval(timer)
})
Guess first: the menu component starts one clock interval every time it opens. With no onDestroy, the menu is opened, closed, opened, closed, then opened again. How many intervals are running?

Three. Every time the menu is opened and then closed, one interval is left behind with no owner and keeps running. This is called a memory leak: work and memory that are never released.

Meaning: onDestroy (also imported from "svelte") runs once, just before the component is removed from the page. Stop everything you started there, such as clearInterval(timer) for the interval kept in timer, or removeEventListener.

⚡ $effect with its cleanup

Write:

$effect(() => {
  const timer = setInterval(() => {
    time = new Date().toLocaleTimeString("en-GB")
  }, 1000)
  return () => clearInterval(timer)
})

Meaning: $effect is a rune (no import needed) that runs its function after the component shows, then again whenever a $state it reads changes. Here that function starts an interval that updates time, a $state, every second. The function it returns, () => clearInterval(timer), is the cleanup: Svelte runs it when the component is removed. So one $effect can replace the onMount and onDestroy pair for an interval.

What you will learn