Performance: onDestroy
This affects cleanup timing and memory usage after a component is removed, impacting interaction responsiveness and memory leaks.
import { onDestroy } from 'svelte'; const onResize = () => { console.log('resize'); }; window.addEventListener('resize', onResize); onDestroy(() => { window.removeEventListener('resize', onResize); });
import { onDestroy } from 'svelte'; // No cleanup of event listener window.addEventListener('resize', () => { console.log('resize'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No cleanup in onDestroy | No change | 0 | 0 | [X] Bad |
| Proper cleanup with onDestroy | No change | 0 | 0 | [OK] Good |
onDestroy function in a Svelte component?onDestroy function runs when the component is about to be removed from the page.onDestroyonDestroy in a Svelte component?import { onDestroy } from 'svelte';onDestroy with a function to run cleanup code: onDestroy(() => { ... });import { onDestroy } from 'svelte';
let timer;
onDestroy(() => {
clearInterval(timer);
});
timer = setInterval(() => {
console.log('Tick');
}, 1000);setInterval that logs 'Tick' every second.onDestroy callback calls clearInterval(timer), which stops the timer when the component is removed.import { onDestroy } from 'svelte';
function handleClick() {
console.log('Clicked');
}
window.addEventListener('click', handleClick);
onDestroy(() => {
window.removeEventListener('click');
});window.removeEventListener('click'); without the handler handleClick, so the listener is not removed.onDestroy to clean up multiple resources: a timer and a custom event listener. Which is the best way to do this in a Svelte component?import { onDestroy } from 'svelte';
let timer = setInterval(() => console.log('Tick'), 1000);
function onCustomEvent() { console.log('Event'); }
window.addEventListener('custom', onCustomEvent);
// What is the correct onDestroy usage?clearInterval(timer) and window.removeEventListener('custom', onCustomEvent) with proper arguments.Pass the test and this pattern moves unknown