javascript / beginner
Snippet
The onDestroy Lifecycle Hook
The onDestroy hook runs when a component is about to be removed from the DOM. It is essential for cleaning up timers, listeners, or subscriptions to prevent memory leaks.
snippet.js
1
2
3
4
5
6
7
import { onDestroy } from 'svelte';const interval = setInterval(() => console.log('tick'), 1000);onDestroy(() => {clearInterval(interval);});
svelte
Breakdown
1
import { onDestroy } from 'svelte';
Imports the lifecycle hook from the Svelte core.
2
onDestroy(() => { clearInterval(interval); });
Schedules a function to stop the interval when the component is destroyed.