Lifecycle Overview
A component’s lifecycle:- Creation - Component is instantiated and mounted to the DOM
- Updates - Reactive effects run when dependencies change
- Destruction - Component is unmounted and cleanup occurs
<script> block executesonMount callbacks run$effect runs when dependencies change$derived values recompute automaticallyonMount
TheonMount function schedules a callback to run when the component is mounted to the DOM:
Key Characteristics
- Runs once per component instance
- Executes after the component is mounted to the DOM
- Does not run during server-side rendering
- Can be called from external modules during initialization
Cleanup with onMount
Return a function fromonMount to run cleanup when the component unmounts:
Common Use Cases
onDestroy
Schedules a callback to run immediately before the component is unmounted:Server-Side Rendering
onDestroy is the only lifecycle hook that runs during server-side rendering:
Effects for Reactivity
Use$effect for side effects that should run when dependencies change:
Effect Timing
Effects run:- After the component is mounted
- In a microtask after state changes
- Updates are batched for performance
- After DOM updates are applied
Effect Cleanup
Return a cleanup function to run when the effect re-runs or the component is destroyed:Pre-DOM Update Effects
Use$effect.pre to run code before the DOM updates:
tick() Function
Usetick to wait for pending DOM updates:
Deprecated: beforeUpdate/afterUpdate
These hooks from Svelte 4 are deprecated. Use$effect.pre and $effect instead:
Advanced: $effect.root
Create effects outside component initialization:Lifecycle Best Practices
- Use onMount for initialization - Fetch data, set up subscriptions, initialize libraries
- Use onDestroy for cleanup - Clear timers, unsubscribe, remove event listeners
- Prefer $effect for reactivity - Let Svelte track dependencies automatically
- Use $effect.pre sparingly - Only when you need pre-DOM-update timing
- Avoid state updates in effects - Use
$derivedinstead when possible
Effect Dependencies
Effects automatically track dependencies:await or in setTimeout are not tracked.