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
onMountfor initialization and data fetching.
-
Use
beforeUpdateandafterUpdatefor DOM synchronization.
-
Use
onDestroyfor cleanup (clearing intervals, unsubscribing).
- Understand the order of lifecycle execution.
3. Lifecycle Execution Order
text
4. onMount — After Component Mounts
svelte
5. onDestroy — Cleanup
svelte
6. beforeUpdate and afterUpdate
svelte
7. onMount Cleanup Return
onMount can return a cleanup function (equivalent to React's useEffect cleanup):
svelte
8. bind:this — Accessing DOM Elements
svelte
9. Common Mistakes
-
Fetch inside
<script>top-level: This runs on the server too (in SSR). Always put async fetching insideonMountfor client-only behavior.
-
Forgetting
onDestroyfor intervals/subscriptions: Memory leaks are the #1 lifecycle bug. EverysetInterval, 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
onMountwith React'suseEffect. What differences exist?
-
Q: What happens if you set state inside
afterUpdatewithout 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.