javascript / beginner
Snippet
The onMount Lifecycle Hook
The onMount function runs after the component is first rendered to the DOM. It is the best place to fetch data, start timers, or interact with third-party libraries that need a DOM element.
snippet.js
1
2
3
4
5
6
7
8
9
10
<script>import { onMount } from 'svelte';onMount(() => {console.log('The component has mounted');return () => {console.log('The component is being destroyed');};});</script>
svelte
Breakdown
1
import { onMount } from 'svelte';
Imports the lifecycle hook from the core Svelte package.
2
return () => { ... }
An optional return function that runs when the component is unmounted (cleanup).