Skip to content

Instantly share code, notes, and snippets.

@o-az
Created June 20, 2024 21:30
Show Gist options
  • Save o-az/99e6c40c023af0817cbbad29f1ad0210 to your computer and use it in GitHub Desktop.
Save o-az/99e6c40c023af0817cbbad29f1ad0210 to your computer and use it in GitHub Desktop.

onNavigate, onMount, onDestroy, and beforeUpdate run in a specific order

example:

<script lang="ts">
  import { onNavigate } from '$app/navigation'
  import { onMount, onDestroy, beforeUpdate, tick } from 'svelte'

  beforeUpdate(async () => {
    console.info('beforeUpdate - tick')
    await tick()
    console.info('beforeUpdate - tick done')
  })

  onMount(() => {
    console.info('onMount - mounted')
    return () => console.info('onMount - destroyed')
  })

  onDestroy(() => {
    console.info('onDestroy')
  })

  onNavigate(to => {
    console.info('onNavigate')
    return () => console.info('onNavigate - cleanup')
  })
</script>

when you visit a page where they're used

the order in which they run is shown through the logs:

beforeUpdate - tick
onMount - mounted
beforeUpdate - tick done

then when you navigate away from the page, the order is:

onNavigate
onDestroy
onMount - destroyed
onNavigate - cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment