This chapters covers the Svelte lifecycle functions:
-
onMount
-
beforeUpdate
-
afterUpdate
-
onDestroy
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 immediately before or after a component is updated. Svelte supports this by allowing registration of functions to be invoked when four specific events occur in the lifecycle of a component instance. These include:
- When it is mounted
- Before it is updated
- After it is updated
- When it is destroyed
The term "mounted" means that the component instance has been added to the DOM.
The term "destroyed" means that the component instance has been removed from the DOM.
A component is "updated" if any of its props change or if any of its state variables change. 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 it not invoked before each component instance is mounted.