Svelte logo

Svelte by Example: Lifecycle Functions

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

In this example, we'll use Svelte's lifecycle functions to hook into an HTML canvas.

Svelte exposes lifecycle functions from the svelte package.

The onMount lifecycle hook executes a callback after the component is mounted. At this point, the component's HTML is rendered in the DOM.

Canvas.svelte
<script>
  import { onMount } from 'svelte';


  onMount(() => {
    const canvas =
      document.querySelector('canvas');
    const context =
      canvas.getContext('2d');

    // …
  });
</script>

<canvas></canvas>

More Lifecycle Functions

beforeUpdate executes a callback before Svelte updates the DOM.

afterUpdate executes a callback after Svelte updates the DOM.

tick returns a callback that resolves after the next time Svelte updates the DOM (or immediately if there are no pending updates)

beforeUpdate(() => {
  // …
});

afterUpdate(() => {
  // …
});
await tick();