Svelte Lifecycle
A lifecycle describes the stages a component passes through, starting from its first appearance on the page and ending when it disappears. Svelte gives you functions to hook into specific stages of this journey.
Why Lifecycle Functions Matter
Some tasks only make sense at a specific moment. Fetching data as soon as a component appears is one example. Cleaning up a timer right before a component disappears is another. Lifecycle functions give you a clear place to write this kind of timed code.
The OnMount Function
The onMount function runs its code once, right after a component first appears on the page.
<script>
import { onMount } from "svelte";
let currentTime = "";
onMount(() => {
currentTime = new Date().toLocaleTimeString();
});
</script>
<p>Loaded at: {currentTime}</p>
The paragraph shows the exact time the component finished loading, calculated the moment onMount runs.
Lifecycle Stages Diagram
Component Created
|
v
onMount runs (component appears on the page)
|
v
Component stays visible, updates happen as data changes
|
v
onDestroy runs (component about to disappear)
|
v
Component removed from the page
The OnDestroy Function
The onDestroy function runs its code right before a component leaves the page, useful for cleanup tasks like clearing a timer.
<script>
import { onMount, onDestroy } from "svelte";
let seconds = 0;
let timer;
onMount(() => {
timer = setInterval(() => {
seconds = seconds + 1;
}, 1000);
});
onDestroy(() => {
clearInterval(timer);
});
</script>
<p>Seconds elapsed: {seconds}</p>
The onMount function starts a repeating timer the moment the component appears. The onDestroy function stops that timer the moment the component disappears, preventing it from running uselessly in the background after the page no longer shows it.
Using Lifecycle Functions For Data Fetching
<script>
import { onMount } from "svelte";
let products = [];
onMount(async () => {
const response = await fetch("https://example.com/api/products");
products = await response.json();
});
</script>
{#each products as product}
<p>{product.name}</p>
{/each}
The fetch call starts the moment the component appears, and the products array fills in once the server responds, triggering the each block to display the results.
A Layman Analogy
Think of a lifecycle as a guest arriving at and leaving a party. OnMount matches the moment the guest walks through the door and settles in, a natural point to introduce themselves. OnDestroy matches the moment the guest says goodbye and heads home, a natural point to collect their coat and return a borrowed umbrella.
Common Lifecycle Use Cases
- Fetching data from a server right when a page loads
- Starting and stopping timers or intervals
- Setting up and removing event listeners tied to the window object
- Logging analytics events when a component appears or disappears
The BeforeUpdate And AfterUpdate Functions
These two functions run around every update to a component, rather than only once at the start or end of its life. BeforeUpdate runs just before the page reflects a change, and afterUpdate runs right after.
<script>
import { beforeUpdate, afterUpdate } from "svelte";
beforeUpdate(() => {
console.log("About to update");
});
afterUpdate(() => {
console.log("Update finished");
});
</script>
These functions fit specialized cases, such as measuring scroll position before a list changes and adjusting it back afterward, and most components never need to use them at all.
Key Points
- onMount runs code once a component first appears on the page
- onDestroy runs code right before a component disappears
- Data fetching commonly happens inside onMount
- Cleanup tasks like clearing timers belong inside onDestroy
