Svelte Lifecycle Explained — Component Lifecycle Functions
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Svelte Lifecycle Explained. We cover key concepts, practical examples, and best practices to help you master this topic.
Svelte lifecycle functions (onMount, onDestroy, beforeUpdate, afterUpdate, tick) run code at specific points during a component's creation, update, and destruction.
What You'll Learn
- onMount for initialization
- onDestroy for cleanup
- beforeUpdate and afterUpdate
- tick for awaiting DOM updates
- Subscription management patterns
Why It Matters
Lifecycle functions manage side effects: fetch data on mount, set up event listeners, start intervals, and clean up resources to prevent memory leaks.
<script>
import { onMount, onDestroy, beforeUpdate, afterUpdate, tick } from "svelte";
let seconds = 0;
let intervalId;
let scrollPosition = 0;
let listElement;
onMount(() => {
intervalId = setInterval(() => seconds++, 1000);
fetch("/api/data").then(r => r.json()).then(data => { /* use data */ });
});
onDestroy(() => {
clearInterval(intervalId);
});
beforeUpdate(() => {
scrollPosition = listElement?.scrollTop || 0;
});
afterUpdate(async () => {
await tick();
if (listElement) listElement.scrollTop = scrollPosition;
});
</script>
<p>Uptime: {seconds}s</p>
<div bind:this={listElement} style="height: 200px; overflow-y: auto;">
{#each Array(100) as _, i}
<p>Item {i + 1}</p>
{/each}
</div>
Expected output: Timer increments on mount, cleanup happens on destroy, scroll position preserves after list updates using tick.
← Previous
Svelte Bindings Explained — Two-Way Data Binding
Next →
Svelte Stores Explained — Reactive State Management
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro