Slim life cycle events

How to use lifecycle events in Svelte

Each component in Svelte will trigger multiple life cycle events, and we can hook them to help us achieve the functions we think of.

In particular, we have

  • onMountTriggered after rendering the component
  • onDestroyTriggered after the component is destroyed
  • beforeUpdateTriggered before the DOM is updated
  • afterUpdateTriggered after the DOM is updated

We can arrange for functions to occur when Svelte triggers these events.

By default, we don’t have access to any of these methods, but we cansveltepackage:

<script>
  import { onMount, onDestroy, beforeUpdate, afterUpdate } from 'svelte'
</script>

Common situationonMountIt is to obtain data from other sources.

This is an example usageonMount:

<script>
  import { onMount } from 'svelte'

onMount(async () => { //do something on mount }) </script>

onDestroyAllows us to clean up data or stop any operations that may have started when the component is initialized, such as using timers or scheduled periodic functionssetInterval.

One thing to note is that if we start fromonMount, Its function andonDestroy-Run when the component is destroyed:

<script>
  import { onMount } from 'svelte'

onMount(async () => { //do something on mount return () => { //do something on destroy } }) </script>

This is a practical example that sets the periodic function to run on mount and deletes it on destroy:

<script>
  import { onMount } from 'svelte'

onMount(async () => { const interval = setInterval(() => { console.log(‘hey, just checking!’) }, 1000)

<span style="color:#66d9ef">return</span> () =&gt; {
  <span style="color:#a6e22e">clearInterval</span>(<span style="color:#a6e22e">interval</span>)
}

}) </script>

Download mine for freeSlim Handbook


More subtle tutorials: