Lifecycle Functions in Svelte: What They Are and How to Use Them
lifecycle functions are special functions that run at specific times during a component's life, like when it is created, updated, or removed. They let you run code to set up, update, or clean up resources tied to the component's existence.How It Works
Think of a Svelte component like a small machine that starts, runs, and then stops. Lifecycle functions are like the buttons you press at different times to control what the machine does. For example, when the machine starts, you might want to prepare some tools; when it runs, you might want to check or update things; and when it stops, you want to clean up.
In Svelte, these lifecycle functions let you run your own code exactly at these moments. For example, onMount runs when the component first appears on the screen, beforeUpdate runs just before the component changes, and onDestroy runs when the component is about to be removed. This helps you manage things like timers, data fetching, or event listeners safely and efficiently.
Example
This example shows how to use onMount and onDestroy to start and stop a timer when a component is shown and removed.
<script> import { onMount, onDestroy } from 'svelte'; let count = 0; let interval; onMount(() => { interval = setInterval(() => { count += 1; }, 1000); return () => { clearInterval(interval); }; }); onDestroy(() => { clearInterval(interval); }); </script> <h1>Timer: {count} seconds</h1>
When to Use
Use lifecycle functions when you need to run code tied to the component's presence on the page. For example:
- Fetching data when the component appears (
onMount). - Setting up event listeners or timers and cleaning them up (
onMountandonDestroy). - Running code before or after the component updates to react to changes (
beforeUpdateandafterUpdate).
They help keep your app efficient and avoid bugs by managing resources properly as components come and go.
Key Points
- onMount: Runs once when the component appears.
- beforeUpdate: Runs before the component updates.
- afterUpdate: Runs after the component updates.
- onDestroy: Runs when the component is removed.
- Use these to manage side effects like timers, subscriptions, or data fetching.