javascript / intermediate
Snippet
Cleaning Up Resources with onDestroy
The onDestroy lifecycle hook is crucial for memory management. It runs just before the component is removed from the DOM, allowing you to clean up timers, event listeners, or manual subscriptions.
snippet.js
1
2
3
4
5
6
7
8
9
import { onDestroy } from 'svelte';const interval = setInterval(() => {console.log('Tick');}, 1000);onDestroy(() => {clearInterval(interval);});
svelte
Breakdown
1
import { onDestroy } from 'svelte';
Imports the lifecycle function that triggers upon component destruction.
2
const interval = setInterval(...);
Sets up a side effect that persists unless manually cleared.
3
clearInterval(interval);
Stops the interval to prevent memory leaks after the component is gone.