In some applications there are actions that need to be performed when a component is added to or removed from the DOM. There are also situations where actions need to be performed before or after a component is updated. Svelte supports this by allowing the registration of functions to be invoked when four specific events occur in the lifecycle of a component instance:
- When it is mounted (added to the DOM)
- Before it is updated
- After it is updated
- When it is destroyed (removed from the DOM)
A component is “updated” if any of its props change or any of its state variables change. Recall that state variables are top-level variables in a component that are used in its HTML.
To register functions for these events, import the provided lifecycle functions from the svelte package:
import {afterUpdate, beforeUpdate, onDestroy, onMount} from 'svelte';
Call these functions, passing them a function to be called when the event occurs. They must be called during component initialization. This means they cannot be called conditionally or be called in a function that is not invoked before each component instance is mounted.