Skip to main content
Svelte Fundamentals
CHAPTER 12 Beginner

Lifecycle Functions in Svelte

Updated: May 18, 2026
5 min read

# CHAPTER 12

Lifecycle Functions in Svelte

1. Chapter Introduction

Every Svelte component has a lifecycle: it is created, it may update multiple times, and eventually it is destroyed. Lifecycle functions let you hook into these moments to run code at precisely the right time — fetch data when mounted, sync scroll position on updates, clean up subscriptions on destroy.

2. Learning Objectives

  • Use onMount for initialization and data fetching.
  • Use beforeUpdate and afterUpdate for DOM synchronization.
  • Use onDestroy for cleanup (clearing intervals, unsubscribing).
  • Understand the order of lifecycle execution.

3. Lifecycle Execution Order

text
1234567891011121314151617
Component Created
      ↓
  Script runs (variables initialized, $: labels set up)
      ↓
  onMount()  ← DOM is ready, safe to query DOM
      ↓
  [User interactions / data changes]
      ↓
  beforeUpdate()  ← Before DOM updates
      ↓
  DOM updates
      ↓
  afterUpdate()   ← After DOM updates
      ↓
Component Destroyed
      ↓
  onDestroy()     ← Cleanup

4. onMount — After Component Mounts

svelte
1234567891011121314151617181920212223242526
<script>
  import { onMount } from &#039;svelte';

  let users = [];
  let loading = true;
  let error = &#039;';

  onMount(async () => {
    try {
      const res = await fetch(&#039;https://jsonplaceholder.typicode.com/users');
      users = await res.json();
    } catch (e) {
      error = e.message;
    } finally {
      loading = false;
    }
  });
</script>

{#if loading}<p>Loading...</p>
{:else if error}<p>Error: {error}</p>
{:else}
  {#each users as user (user.id)}
    <p>{user.name} — {user.email}</p>
  {/each}
{/if}

5. onDestroy — Cleanup

svelte
12345678910111213141516171819
<script>
  import { onMount, onDestroy } from &#039;svelte';

  let seconds = 0;
  let intervalId;

  onMount(() => {
    intervalId = setInterval(() => {
      seconds++;
    }, 1000);
  });

  onDestroy(() => {
    clearInterval(intervalId); // Critical! Prevents memory leaks
    console.log(&#039;Timer component destroyed, interval cleared.');
  });
</script>

<p>Timer: {seconds}s</p>

6. beforeUpdate and afterUpdate

svelte
123456789101112131415161718192021222324252627
<script>
  import { beforeUpdate, afterUpdate } from &#039;svelte';

  let messages = [];
  let chatContainer;

  beforeUpdate(() => {
    // Check if user is near the bottom before update
    if (chatContainer) {
      const { scrollTop, scrollHeight, clientHeight } = chatContainer;
      // Store scroll info before DOM updates
    }
  });

  afterUpdate(() => {
    // Auto-scroll to bottom after new message added
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }
  });
</script>

<div class="chat" bind:this={chatContainer}>
  {#each messages as msg}
    <div class="message">{msg}</div>
  {/each}
</div>

7. onMount Cleanup Return

onMount can return a cleanup function (equivalent to React's useEffect cleanup):
svelte
12345678910111213
<script>
  import { onMount } from &#039;svelte';

  onMount(() => {
    const handler = (e) => console.log(&#039;Key pressed:', e.key);
    window.addEventListener(&#039;keydown', handler);

    // Return cleanup function — runs on destroy
    return () => {
      window.removeEventListener(&#039;keydown', handler);
    };
  });
</script>

8. bind:this — Accessing DOM Elements

svelte
12345678910
<script>
  import { onMount } from &#039;svelte';
  let inputEl;

  onMount(() => {
    inputEl.focus(); // Auto-focus the input on mount
  });
</script>

<input bind:this={inputEl} placeholder="Auto-focused!" />

9. Common Mistakes

  • Fetch inside <script> top-level: This runs on the server too (in SSR). Always put async fetching inside onMount for client-only behavior.
  • Forgetting onDestroy for intervals/subscriptions: Memory leaks are the #1 lifecycle bug. Every setInterval, event listener, or manual store subscription needs a corresponding cleanup.

10. MCQs

Question 1

When does onMount run?

Question 2

What is onMount primarily used for?

Question 3

When does onDestroy run?

Question 4

What should you do in onDestroy?

Question 5

When does beforeUpdate run?

Question 6

What is afterUpdate useful for?

Question 7

What does bind:this={myEl} do?

Question 8

Can onMount return a cleanup function?

Question 9

Why should data fetching go in onMount rather than top-level <script>?

Question 10

What is the correct order of lifecycle execution?

11. Interview Questions

  • Q: Compare Svelte's onMount with React's useEffect. What differences exist?
  • Q: What happens if you set state inside afterUpdate without a guard condition?

12. Summary

Svelte's lifecycle functions are minimal and purposeful. onMount handles initialization and data fetching. onDestroy handles cleanup. beforeUpdate and afterUpdate provide hooks for DOM synchronization. The onMount cleanup return pattern is an elegant way to colocate setup and teardown logic.

13. Next Chapter Recommendation

Our app is one page. In Chapter 13: Routing in Svelte, we implement client-side routing to create a multi-page SPA experience without reloading the browser.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·