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
onMount
Triggered after rendering the componentonDestroy
Triggered after the component is destroyedbeforeUpdate
Triggered before the DOM is updatedafterUpdate
Triggered 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 cansvelte
package:
<script>
import { onMount, onDestroy, beforeUpdate, afterUpdate } from 'svelte'
</script>
Common situationonMount
It is to obtain data from other sources.
This is an example usageonMount
:
<script>
import { onMount } from 'svelte'
onMount(async () => {
//do something on mount
})
</script>
onDestroy
Allows 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> () => {
<span style="color:#a6e22e">clearInterval</span>(<span style="color:#a6e22e">interval</span>)
}
})
</script>
Download mine for freeSlim Handbook
More subtle tutorials:
- Getting started with Svelte-short tutorial
- How to use props in Svelte
- How to import components in Svelte
- How to export functions and variables from Svelte components
- Slim template: conditional logic
- How to re-render Svelte components on demand
- Slim slot
- How to add comments in Svelte templates
- Slim binding
- Handling status updates in Svelte
- Reactive statements in Svelte
- Slim life cycle events
- Slim template: loop
- Resolve the promise in the Svelte template
- Dealing with Svelte's activities
- Svelte's cross-component state management
- How to access URL parameters in Sapper outside the script module
- How to dynamically apply CSS in Svelte
- How to redirect to URL in Sapper
- How to simulate for loop in Svelte template