Svelte Lifecycle hooks tutorial

by Sai gowtham2min read
Svelte Lifecycle hooks tutorial

In this tutorial, we are going to learn about a different type of svelte lifecycle hooks using examples.

Lifecycle hooks

Lifecycle hooks are javascript methods which run at different phases of a component.

onMount

The onMount hook runs after a component is rendered into the dom, this is a good place to make network requests.

example:

Fetch.svelte
<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:

Counter.svelte
<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:

Counter.svelte
<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:

Timer.svelte
<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>