The onDestroy function lets you run code when a Svelte component is removed from the page. This helps clean up things like timers or event listeners so your app stays fast and tidy.
onDestroy in Svelte
Introduction
Syntax
Svelte
import { onDestroy } from 'svelte'; onDestroy(() => { // cleanup code here });
You import onDestroy from 'svelte' to use it.
The function you pass to onDestroy runs once when the component is removed.
Examples
Svelte
import { onDestroy } from 'svelte'; onDestroy(() => { console.log('Component is gone'); });
Svelte
import { onDestroy } from 'svelte'; const interval = setInterval(() => { console.log('Tick'); }, 1000); onDestroy(() => { clearInterval(interval); });
Sample Program
This component increases a number every second. When the component is removed, the timer stops and a message logs in the console.
Svelte
<script> import { onDestroy } from 'svelte'; let count = 0; const interval = setInterval(() => { count += 1; }, 1000); onDestroy(() => { clearInterval(interval); console.log('Interval cleared'); }); </script> <p>Count: {count}</p>
Important Notes
Always clean up timers, listeners, or subscriptions in onDestroy to avoid memory leaks.
onDestroy runs only once per component instance.
Summary
onDestroy runs code when a Svelte component is removed.
Use it to clean up timers, event listeners, or other resources.
Helps keep your app fast and bug-free by avoiding leftover tasks.
Practice
1. What is the main purpose of the
onDestroy function in a Svelte component?easy
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]
Hint: Remember: onDestroy cleans up when component leaves [OK]
Common Mistakes:
- Confusing onDestroy with onMount
- Thinking onDestroy runs on data update
- Using onDestroy to initialize state
2. Which of the following is the correct way to import and use
onDestroy in a Svelte component?easy
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]
Hint: Use named import and call onDestroy with a function [OK]
Common Mistakes:
- Using default import instead of named import
- Assigning onDestroy instead of calling it
- Calling a non-existent cleanup method
3. Consider this Svelte component code:
What happens when this component is removed from the page?
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?
medium
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]
Hint: onDestroy stops timers to prevent leftover logs [OK]
Common Mistakes:
- Thinking timer keeps running after component removal
- Confusing clearInterval with setTimeout
- Assuming onDestroy runs multiple times
4. This Svelte component tries to clean up an event listener on destroy:
What is wrong with this code?
import { onDestroy } from 'svelte';
function handleClick() {
console.log('Clicked');
}
window.addEventListener('click', handleClick);
onDestroy(() => {
window.removeEventListener('click');
});What is wrong with this code?
medium
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]
Hint: Always pass event and handler to removeEventListener [OK]
Common Mistakes:
- Omitting the handler function in removeEventListener
- Adding listeners inside onDestroy instead of removing
- Defining handler inside onDestroy causing scope issues
5. You want to use
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?hard
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]
Hint: Put all cleanup code inside one onDestroy callback [OK]
Common Mistakes:
- Using multiple onDestroy calls instead of one
- Omitting handler in removeEventListener
- Calling clearInterval without timer argument
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
