0
0
Svelteframework~5 mins

Why lifecycle hooks run code at key moments in Svelte

Choose your learning style9 modes available
Introduction

Lifecycle hooks let you run code exactly when your component starts, updates, or ends. This helps you control what happens at important times.

When you want to fetch data right after a component appears on the screen.
When you need to clean up timers or event listeners before a component disappears.
When you want to react to changes in component data or props.
When you want to set up animations when a component is created.
When you want to log or track component behavior during its life.
Syntax
Svelte
import { onMount, beforeUpdate, afterUpdate, onDestroy } from 'svelte';

onMount(() => {
  // code to run when component is added to the page
});

beforeUpdate(() => {
  // code to run before the component updates
});

afterUpdate(() => {
  // code to run after the component updates
});

onDestroy(() => {
  // code to run when the component is removed
});

Each hook runs at a specific time in the component's life.

Use onMount for setup, onDestroy for cleanup.

Examples
This runs code once when the component appears.
Svelte
import { onMount } from 'svelte';

onMount(() => {
  console.log('Component is ready!');
});
This runs code once just before the component is removed.
Svelte
import { onDestroy } from 'svelte';

onDestroy(() => {
  console.log('Component is leaving.');
});
These run code before and after the component updates.
Svelte
import { beforeUpdate, afterUpdate } from 'svelte';

beforeUpdate(() => {
  console.log('About to update');
});

afterUpdate(() => {
  console.log('Just updated');
});
Sample Program

This component starts a timer when it appears and increases a count every second. When the component is removed, it stops the timer to avoid problems.

Svelte
<script>
  import { onMount, onDestroy } from 'svelte';

  let timer;
  let count = 0;

  onMount(() => {
    console.log('Component mounted');
    timer = setInterval(() => {
      count += 1;
      console.log(`Count is now ${count}`);
    }, 1000);
  });

  onDestroy(() => {
    clearInterval(timer);
    console.log('Component destroyed and timer cleared');
  });
</script>

<p>Count: {count}</p>
OutputSuccess
Important Notes

Always clean up resources like timers or event listeners in onDestroy to avoid memory leaks.

Lifecycle hooks help keep your component's behavior organized and predictable.

Summary

Lifecycle hooks run code at key moments in a component's life.

Use onMount to start things and onDestroy to clean up.

Hooks like beforeUpdate and afterUpdate help react to changes.