Svelte logo

Svelte by Example: Lifecycle Functions

Svelte exposes a few functions to execute code during component lifecycle events.

In this example, we'll update a todo list when the component is mounted.

onMount executes a callback after the component is mounted in the browser. It doesn't run during server-side rendering.

Return a function to clean up when the component is removed. Here, we'll stop our timer.

TodoList.svelte
<script>
  import { onMount } from 'svelte';
  let seconds = $state(0);

  onMount(() => {
    const timer = setInterval(() => seconds++, 1000);
    return () => clearInterval(timer);
  });
</script>

<p>You've been working on your todos for {seconds} seconds.</p>

Waiting for the DOM

tick returns a promise that resolves after pending state changes have been applied to the DOM.

After showing our input, we'll wait for Svelte to render it before moving focus to it.

AddTodo.svelte
<script>
  import { tick } from 'svelte';
  let editing = $state(false);
  let input = $state();

  async function startEditing() {
    editing = true;
    await tick();
    input.focus();
  }
</script>

<button onclick={startEditing}>Add a todo</button>
{#if editing}
  <input bind:this={input} aria-label="New todo" />
{/if}

More Lifecycle Functions

onDestroy runs a callback when a component is removed. Unlike onMount, it also runs during server-side rendering.

In Svelte 5, updates belong to individual effects, not the whole component. Use $effect.pre to run before the DOM updates, or $effect to run after it updates. Both track the reactive values they read, and neither runs on the server.