Lifecycle Events In Svelte

manyeya

Khutso siema

Posted on October 18, 2019

Lifecycle Events In Svelte

Getting to know Lifecycle Events in Svelte

Every component in svelte has a lifecycle that starts when it is created, and ends when it is destroyed.

N.B

Lifecycle functions must be called while the component is initialising so that the callback is bound to the component instance — not (say) in a setTimeout.

Lifecycle functions in svelte include

  • onMount fired after the component is rendered
  • onDestroy fired after the component is destroyed
  • beforeUpdate fired before the DOM is updated
  • afterUpdate fired after the DOM is updated

and the special tick function

onMount

The most frequently used is onMount, which runs after the component is first rendered to the DOM.
A common use for onMount is to fetch data from other sources.

Here’s a sample usage of onMount:

<script>
 import { onMount } from "svelte";

let myTodo;
  onMount(async()=>{
     const response = await fetch("https://jsonplaceholder.typicode.com/todos/1")
      const todo = await response.json();
      myTodo = todo
  });
</script>

<div>
  {#if myTodo}
    <ul>
      <li>{myTodo.title}</li>
    </ul>
  {:else}
    <p>loading.....</p>
  {/if}
</div>

Enter fullscreen mode Exit fullscreen mode

onDestroy

onDestroy allows us to cleanup data or stop any operation we might have started at the component initialization, like timers or event listeners which prevents us from memory leaks.

Here’s a sample usage of onDestroy:


<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>

Enter fullscreen mode Exit fullscreen mode

beforeUpdate and afterUpdate

The beforeUpdate function schedules work to happen immediately before the DOM has been updated. afterUpdate is its counterpart, used for running code once the DOM is in sync with your data.

beforeUpdate

The beforeUpdate does exactly what it implies,in technical terms you can say it schedules a callback function to runs immediately before the component is updated after any state change.

Here’s an 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>

Enter fullscreen mode Exit fullscreen mode

afterUpdate

afterUpdate is beforeUpdate's counterpart, used for running code once the DOM is in sync with your data.

Here’s an 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>

Enter fullscreen mode Exit fullscreen mode

Tick

At the start of this post i mentioned that the tick lifecycle function was special,why is it special?well...

The tick function is unlike other lifecycle functions in that you can call it any time, not just when the component first initialises.
It returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes).

Here’s an example:

<script>
    import { beforeUpdate, tick } from 'svelte';

    beforeUpdate(async () => {
        console.log('the component is about to update');
        await tick();
        console.log('the component just updated');
    });
</script>
Enter fullscreen mode Exit fullscreen mode

A better usecase example of this function can be found on the svelte
website.Tick Example


Thanks for reading and stay tuned!

💖 💪 🙅 🚩
manyeya
Khutso siema

Posted on October 18, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Lifecycle Events In Svelte
javascript Lifecycle Events In Svelte

October 18, 2019