SvelteJS component’s lifecycle
Components complete a full life cycle from creation to destruction. During that period, Svelte provides some handful of functions that allow us to run code at specific moments.
Lets take a look at those functions.
- onMount
- beforeUpdate
- afterUpdate
- onDestroy
- tick
onMount:
onMount(callback: () => () => void)
It is triggered after the component is first rendered to dom. It must be called during the component’s initialization. Some tasks which can be performed under this method are :
- timers/intervals functions
- fetching data
If a function is returned from onMount, that it will be executed after component is destroyed.
Live demo here
<script> import { onMount } from 'svelte';
let counter = 0; onMount(() => {
console.log('the component has mounted'); // get dom element by id
console.log(document.getElementById('tag')); //intervals functions
const interval = setInterval(() => {
counter = counter + 1;
}, 1000); //If a function is returned from onMount, it will be called when the component is unmounted.
return () => clearInterval(interval);
});
</script><h1 id="tag">
{counter}
</h1>
beforeUpdate & afterUpdate:
beforeUpdate(callback: () => void)
afterUpdate(callback: () => void)
If there is any state change, then component needs to update and before any update, ‘beforeUpdate’ is triggered. ‘beforeMount’ is called for first time when component is mounted.
Counterpart of ‘beforeUpdate’ is ‘afterUpdate’ which is called after component update is completed.
Live demo here
<script>
import { onMount, beforeUpdate, afterUpdate } from 'svelte';
let counter = 0; beforeUpdate(() => {
console.log('the component is going to be updated');
}); afterUpdate(() => {
console.log('the component has been updated');
}); onMount(() => {
const interval = setInterval(() => {
counter = counter + 1;
}, 1000);
return () => clearInterval(interval);
});
</script>
<h1>{counter}</h1>
onDestroy
onDestroy(callback: () => void)
Any task which need to be done after component is destroyed should be done inside ‘onDestroy’.
<script>
import { onDestroy } from 'svelte';
onDestroy(() => {
console.log('the component is being destroyed');
});
</script>
tick:
promise: Promise = tick()
Its different from other life cycle methods. It can be called anytime anywhere after the component is mounted.
If one update is running and has not been completed, ‘tick’ method helps to control or pause the other upcoming updates until the current update is completed. It returns a promise that resolves as soon as any pending state changes have been applied to the DOM.
Live demo here
<script>
import {beforeUpdate, tick } from 'svelte'; let counter = 1; setInterval(() => {
counter++;
},2000); beforeUpdate(async () => {
console.log('the component is about to update');
await tick();
console.log('the component just updated');
});</script><p>Number : {counter}</p>