0 day streak
javascript / intermediate
Snippet

Resource Cleanup with onDestroy

Lifecycle management is crucial for performance. The 'onDestroy' hook runs just before the component is removed from the DOM, making it the ideal place to clear intervals, unsubscribe from global events, or close WebSocket connections to prevent memory leaks.

snippet.js
javascript
1
2
3
4
5
6
7
8
<script>
import { onDestroy } from 'svelte';
const interval = setInterval(() => console.log('Tick'), 1000);
onDestroy(() => {
clearInterval(interval);
});
</script>
svelte
Breakdown
1
onDestroy(() => { ... })
Schedules a function to run when the component instance is being destroyed.