Component Lifecycle

Loading concept...

🎭 The Life Story of a Svelte Component

The Birthday Party Analogy

Imagine your Svelte component is like throwing a birthday party. Every party has special moments:

  • Setting Up 🎈 (onMount) - Decorations go up, food arrives
  • Cleanup Time 🧹 (onDestroy) - Party ends, trash gets thrown away
  • Waiting for Paint to Dry ⏳ (tick) - Sometimes you need to wait before the next step
  • The Grand Entrance 🚪 (mount) - The moment guests actually arrive

Let’s explore each magical moment!


🎈 onMount: The Setup Crew

What Is It?

onMount runs right after your component appears on screen. Think of it like:

“The decorations are hung, the lights are on—NOW we can start the party!”

When to Use It?

  • Fetch data from the internet
  • Start animations
  • Connect to things outside Svelte (like maps or charts)
  • Set up timers

Simple Example

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

  let message = 'Loading...';

  onMount(() => {
    // This runs when component shows up
    message = 'Hello! I am ready!';
  });
</script>

<p>{message}</p>

What happens:

  1. First, you see “Loading…”
  2. Component appears on screen
  3. onMount runs
  4. Now you see “Hello! I am ready!”

Fetching Data Example

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

  let users = [];

  onMount(async () => {
    const response = await fetch('/api/users');
    users = await response.json();
  });
</script>

{#each users as user}
  <p>{user.name}</p>
{/each}

🎯 Key Point

onMount only runs in the browser, not on the server. Perfect for browser-only stuff!


🧹 onDestroy: The Cleanup Crew

What Is It?

onDestroy runs right before your component disappears. Like saying:

“Party’s over! Let’s clean up before we leave.”

Why Is It Important?

Without cleanup, you get “memory leaks”—like leaving the water running forever!

Simple Example

<script>
  import { onDestroy } from 'svelte';

  const timer = setInterval(() => {
    console.log('Tick!');
  }, 1000);

  onDestroy(() => {
    // Stop the timer when leaving
    clearInterval(timer);
  });
</script>

<p>Timer is running...</p>

Real-World Pattern

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

  let count = 0;
  let interval;

  onMount(() => {
    // Start counting
    interval = setInterval(() => {
      count += 1;
    }, 1000);
  });

  onDestroy(() => {
    // Stop counting
    clearInterval(interval);
  });
</script>

<p>Count: {count}</p>

💡 Pro Tip: Return from onMount

You can return a cleanup function from onMount—it works like onDestroy!

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

  onMount(() => {
    const timer = setInterval(() => {
      console.log('Running');
    }, 1000);

    // This runs on destroy!
    return () => clearInterval(timer);
  });
</script>

⏳ tick: Waiting for the Screen to Update

What Is It?

tick is like pressing “pause” until Svelte finishes painting the screen.

“Wait! Let the paint dry before touching the wall!”

Why Do We Need It?

Sometimes you change a value but need to wait for the screen to actually update before doing the next thing.

The Problem Without tick

<script>
  let text = '';
  let textarea;

  function addText() {
    text += 'Hello! ';
    // Oops! The textarea hasn't updated yet!
    textarea.scrollTop = textarea.scrollHeight;
  }
</script>

The Solution With tick

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

  let text = '';
  let textarea;

  async function addText() {
    text += 'Hello! ';
    await tick(); // Wait for screen update
    // Now it works!
    textarea.scrollTop = textarea.scrollHeight;
  }
</script>

<textarea bind:this={textarea}>{text}</textarea>
<button on:click={addText}>Add</button>

Visual Flow

graph TD A[Change Data] --> B[Call tick] B --> C[Wait...] C --> D[Screen Updates] D --> E[Continue Code]

Another Example

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

  let items = [];
  let list;

  async function addItem() {
    items = [...items, 'New Item'];
    await tick();
    // Now scroll to see new item
    list.lastChild.scrollIntoView();
  }
</script>

<ul bind:this={list}>
  {#each items as item}
    <li>{item}</li>
  {/each}
</ul>

🚪 mount: The Modern Entrance (Svelte 5)

What Is It?

mount is the new way in Svelte 5 to put a component on the page. Think of it as:

“Here’s the guest. Here’s the room. Now make the entrance happen!”

The Old Way vs New Way

// OLD (Svelte 4)
const app = new App({ target: document.body });

// NEW (Svelte 5)
import { mount } from 'svelte';
const app = mount(App, { target: document.body });

Basic Example

import { mount } from 'svelte';
import App from './App.svelte';

const app = mount(App, {
  target: document.getElementById('app')
});

With Props

import { mount } from 'svelte';
import Greeting from './Greeting.svelte';

const greeting = mount(Greeting, {
  target: document.body,
  props: {
    name: 'World',
    count: 5
  }
});

Why the Change?

Old Way New Way
Uses new keyword Uses mount() function
Less clear More explicit
Class-based Function-based

🎭 The Complete Picture

Lifecycle Flow

graph TD A[mount - Create Component] --> B[Component Renders] B --> C[onMount Runs] C --> D[Component Lives] D --> E[Changes Happen] E --> F[tick - Wait for Update] F --> D D --> G[Time to Leave] G --> H[onDestroy Runs] H --> I[Component Gone]

All Together Example

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

  let messages = [];
  let chatBox;
  let ws;

  onMount(() => {
    // Connect to chat
    ws = new WebSocket('wss://chat.example.com');

    ws.onmessage = async (event) => {
      messages = [...messages, event.data];
      await tick();
      chatBox.scrollTop = chatBox.scrollHeight;
    };

    // Cleanup on destroy
    return () => ws.close();
  });
</script>

<div bind:this={chatBox}>
  {#each messages as msg}
    <p>{msg}</p>
  {/each}
</div>

🧠 Quick Memory Tricks

Function When Think Of It As
onMount After appearing “I’m here!” 🎉
onDestroy Before leaving “Goodbye!” 👋
tick Wait for paint “Hold on…” ⏸️
mount Create component “Let’s begin!” 🚀

⚠️ Common Mistakes

❌ Forgetting Cleanup

<!-- BAD -->
<script>
  setInterval(() => console.log('leak!'), 1000);
</script>

<!-- GOOD -->
<script>
  import { onDestroy } from 'svelte';
  const timer = setInterval(() => console.log('ok'), 1000);
  onDestroy(() => clearInterval(timer));
</script>

❌ Not Using async with tick

<!-- BAD -->
<script>
  import { tick } from 'svelte';
  function update() {
    data = newData;
    tick(); // Doesn't wait!
    doSomething();
  }
</script>

<!-- GOOD -->
<script>
  import { tick } from 'svelte';
  async function update() {
    data = newData;
    await tick(); // Now it waits!
    doSomething();
  }
</script>

🎓 You Made It!

Now you understand the life of a Svelte component:

  1. mount brings it to life
  2. onMount sets things up
  3. tick waits for updates
  4. onDestroy cleans up after

Your components will now be well-behaved party guests—setting up properly, cleaning up after themselves, and waiting their turn!

🚀 Go build something awesome!

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.