Svelte lifecycle hooks are functions that let you run code at specific moments in a component’s life, such as when it is created, when its state changes, or when it is destroyed. You use them by importing onMount, beforeUpdate, afterUpdate, and onDestroy from svelte and calling them inside your component’s <script> block. This article explains what each hook does, how they differ from other frameworks, and how to use them correctly in your own projects.
Background: Why Svelte Doesn’t Need a Lifecycle for Rendering
Most frameworks (React, Vue) use a virtual DOM and a lifecycle that includes mounting, updating, and unmounting phases. Svelte compiles your components into efficient imperative JavaScript that directly manipulates the DOM. Because of this, Svelte’s lifecycle is simpler: you only have four main hooks, and they map directly to real browser events rather than framework-level abstractions.
The key difference is that Svelte’s onMount runs after the component is first rendered to the DOM, not before. This is unlike React’s useEffect which runs after paint but can also run on updates. In Svelte, you explicitly choose which hook runs when.
The Four Core Hooks: What They Do and When to Use Them
onMount
Runs once, after the component is first rendered and attached to the document. Use it for:
- Fetching data from an API
- Starting timers or intervals
- Adding event listeners on
windowordocument - Initializing third-party libraries that need a DOM element
Example:
import { onMount } from 'svelte';
let user = null;
onMount(async () => {
const res = await fetch('/api/user');
user = await res.json();
});
If you return a function from onMount, it will be called when the component is destroyed – this is a convenient place to clean up timers or listeners.
beforeUpdate
Runs immediately before the DOM is updated after a state change. This is the right place to read the old DOM state (e.g., scroll position) because the DOM hasn’t been changed yet. It does not run on the initial render.
afterUpdate
Runs after the DOM has been updated. Use it to interact with the new DOM – for example, to focus an input or adjust a scroll position based on new content. Like beforeUpdate, it does not run on the initial render.
onDestroy
Runs when the component is removed from the DOM. Use it to clean up: clear intervals, remove event listeners, cancel fetch requests, or destroy third-party widget instances. This is the Svelte equivalent of React’s useEffect cleanup function.
How to Choose the Right Hook
A simple rule of thumb:
- Need to run something once after the component appears? →
onMount - Need to read the DOM before a change? →
beforeUpdate - Need to read the DOM after a change? →
afterUpdate - Need to clean up when the component goes away? →
onDestroy
For example, if you have a chat window that should scroll to the bottom when a new message arrives, you would use afterUpdate to set scrollTop after the list has grown. If you need to save the current scroll position before new messages are added, use beforeUpdate.
Common Mistakes and Misconceptions
Mistake 1: Using onMount to set initial state. If you set a variable inside onMount, the component will render once with the default value, then re-render when the value changes. This can cause a flash of empty content. Instead, initialize the variable with a sensible default or use a reactive statement ($:) if the value depends on other state.
Mistake 2: Forgetting that beforeUpdate and afterUpdate don’t run on initial render. If you need code to run both initially and on updates, you have to call that code manually in onMount or use a reactive statement.
Mistake 3: Not cleaning up in onDestroy. Intervals and event listeners left behind will cause memory leaks and unexpected behavior. Always clear them.
Misconception: onMount runs before the DOM is ready. It runs after the component is in the DOM, so you can safely query elements with bind:this or document.querySelector inside it.
Comparison with Other Frameworks
React’s useEffect with an empty dependency array is similar to onMount, but useEffect also handles updates and cleanup in one place. Vue’s onMounted, onUpdated, and onUnmounted are nearly identical to Svelte’s hooks. The main difference is that Svelte’s hooks are compiled away – they don’t exist at runtime as a generic system, which makes them slightly faster and more predictable.
When Lifecycle Hooks Are Not Enough
For complex state that spans multiple components, you might use Svelte’s stores instead of lifecycle hooks. Stores can be updated from anywhere, and you can subscribe to them with $store syntax. Lifecycle hooks are for component-local side effects; stores are for shared state.
Also, for animations or transitions, Svelte provides built-in transition: directives that handle their own lifecycle – you don’t need to manually trigger CSS classes in afterUpdate.
Frequently Asked Questions
Does onMount run on the server?
No. onMount only runs in the browser. In SSR (server-side rendering), it is skipped entirely. If you need code to run on both server and client, put it directly in the <script> block (but be careful with browser-only APIs).
Can I have multiple onMount calls in one component?
Yes. You can call onMount as many times as you like. They will all run in the order they are defined, after the component is mounted.
What happens if I return a function from beforeUpdate?
Nothing special – the return value is ignored. Only the function returned from onMount is used as a cleanup function.
Is there a way to run code before the component is created?
No. Svelte does not have a beforeCreate hook. Code in the <script> block runs before the component is instantiated, so you can put initialization logic there, but it runs in the module scope, not per-instance (unless you use export let or reactive declarations).
Do lifecycle hooks work in Svelte 5 with runes?
Yes, the same hooks (onMount, beforeUpdate, etc.) are still available and work the same way. Svelte 5 adds runes ($state, $effect) but the lifecycle hooks remain for side effects. $effect is a more powerful replacement for beforeUpdate/afterUpdate in many cases, but the classic hooks are still fully supported.
Why is my afterUpdate not firing when I change a prop?
It fires, but only if the component actually re-renders. If the parent passes the same value, Svelte may skip the update. Also, if you change a variable that is not used in the template, Svelte may not trigger an update at all. Make sure the changed value is referenced in the markup or in a reactive statement.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Gadgets After Support Ends: Do They Improve?
- Delete Google Search Results About You
- OnePlus Buds Pro 3 Price Drop: Are They Worth It?
- Cloud Migration Ways to Prepare
- Remote Work Productivity Hacks That Actually Work
- Epic Games Removes Dark and Darker? Fact Check