Svelte Lifecycle hooks tutorial
In this tutorial, we are going to learn about different types of available lifecycle hooks in Svelte.
Lifecycle hooks
Lifecycle hooks are javascript methods which run at different phases of a component creation to destruction.
onMount
The onMount hook runs after a component is rendered into the dom, this is a good place to make network requests.
example:
<script>
import { onMount } from "svelte";
let mytodo;
onMount( fetch("https://jsonplaceholder.typicode.com/todos/1") .then(response => response.json()) .then(todo => { mytodo = todo; }) );</script>
<div>
{#if mytodo}
<ul>
<li>{mytodo.id}</li>
</ul>
{:else}
<p>loading.....</p>
{/if}
</div>In the above code, we first imported the onMount hook from the svelte package then we passed fetch as argument to the onMount hook.
beforeUpdate
The beforeUpdate lifecycle hook runs immediately before a dom is updated.
example:
<script>
import { beforeUpdate} from "svelte"; let count = 1;
beforeUpdate(function() { console("You can see me before count value is updated"); });</script>
<div>
<h1>{count}</h1>
<button on:click={() => count++}>Increment</button>
</div>afterUpdate
The afterUpdate lifecycle hooks runs after a dom is updated.(it means the state is completely synced with the view).
example:
<script>
import { afterUpdate} from "svelte"; let count = 1;
afterUpdate(function() { console("You can see me after count value is updated"); });</script>
<div>
<h1>{count}</h1>
<button on:click={() => count++}>Increment</button>
</div>onDestroy
The onDestroy lifecycle hook runs whenever a component is destroyed.This a best place to clear timer or event listeners which prevents us from memory leaks.
example:
<script>
import { onDestroy } from "svelte"; let date = new Date();
let timer = setInterval(() => { date = new Date(); }, 1000); // clears the timer when a component is destroyed
onDestroy(function() { clearInterval(timer); });
</script>
<p>{date.toLocaleTimeString()}</p>

