What if your app could clean up after itself perfectly every time you leave a page?
Why onDestroy in Svelte? - Purpose & Use Cases
Imagine you create a popup or a timer in your app, and when you close or leave that part, you forget to stop the timer or remove the popup.
Without cleaning up, timers keep running, event listeners stay active, and memory fills up. This makes your app slow and buggy over time.
The onDestroy function in Svelte lets you run cleanup code automatically when a component is removed, keeping your app fast and error-free.
const timer = setInterval(() => { console.log('tick'); }); // but no clearInterval when doneimport { onDestroy } from 'svelte'; const timer = setInterval(() => { console.log('tick'); }, 1000); onDestroy(() => clearInterval(timer));
You can safely create temporary effects or listeners that clean themselves up, making your app smooth and reliable.
When showing a live chat widget, onDestroy stops the message polling when the chat closes, saving resources.
onDestroy runs cleanup code when a component is removed.
It prevents memory leaks and unwanted background tasks.
Using it keeps your app fast and bug-free.
Practice
onDestroy function in a Svelte component?Solution
Step 1: Understand the lifecycle of a Svelte component
TheonDestroyfunction runs when the component is about to be removed from the page.Step 2: Identify the purpose of
It is used to clean up things like timers or event listeners to avoid bugs or memory leaks.onDestroyFinal Answer:
To run cleanup code when the component is removed from the page -> Option AQuick Check:
onDestroy = cleanup on removal [OK]
- Confusing onDestroy with onMount
- Thinking onDestroy runs on data update
- Using onDestroy to initialize state
onDestroy in a Svelte component?Solution
Step 1: Check the import syntax
The correct import is a named import:import { onDestroy } from 'svelte';Step 2: Check how to use onDestroy
You callonDestroywith a function to run cleanup code:onDestroy(() => { ... });Final Answer:
import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ }); -> Option CQuick Check:
Correct import and call syntax = import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ }); [OK]
- Using default import instead of named import
- Assigning onDestroy instead of calling it
- Calling a non-existent cleanup method
import { onDestroy } from 'svelte';
let timer;
onDestroy(() => {
clearInterval(timer);
});
timer = setInterval(() => {
console.log('Tick');
}, 1000);What happens when this component is removed from the page?
Solution
Step 1: Understand the timer setup
The code sets a repeating timer withsetIntervalthat logs 'Tick' every second.Step 2: Analyze the onDestroy cleanup
TheonDestroycallback callsclearInterval(timer), which stops the timer when the component is removed.Final Answer:
The interval timer stops and no more 'Tick' logs appear -> Option DQuick Check:
onDestroy clears timer = stops logs [OK]
- Thinking timer keeps running after component removal
- Confusing clearInterval with setTimeout
- Assuming onDestroy runs multiple times
import { onDestroy } from 'svelte';
function handleClick() {
console.log('Clicked');
}
window.addEventListener('click', handleClick);
onDestroy(() => {
window.removeEventListener('click');
});What is wrong with this code?
Solution
Step 1: Check removeEventListener usage
To remove an event listener, you must pass both the event type and the exact handler function.Step 2: Identify the missing argument
The code callswindow.removeEventListener('click');without the handlerhandleClick, so the listener is not removed.Final Answer:
removeEventListener is missing the event handler function argument -> Option AQuick Check:
removeEventListener needs event and handler [OK]
- Omitting the handler function in removeEventListener
- Adding listeners inside onDestroy instead of removing
- Defining handler inside onDestroy causing scope issues
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?Solution
Step 1: Combine cleanup tasks in one onDestroy callback
onDestroy accepts a single function where you can clean multiple resources.Step 2: Correctly clear timer and remove event listener
UseclearInterval(timer)andwindow.removeEventListener('custom', onCustomEvent)with proper arguments.Final Answer:
onDestroy(() => { clearInterval(timer); window.removeEventListener('custom', onCustomEvent); }); -> Option BQuick Check:
Single onDestroy with all cleanup calls [OK]
- Using multiple onDestroy calls instead of one
- Omitting handler in removeEventListener
- Calling clearInterval without timer argument
Ready to prove it?
Pass the test and this pattern moves unknown
