0
0
Svelteframework~5 mins

onDestroy in Svelte - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the onDestroy lifecycle function in Svelte?
The onDestroy function runs cleanup code when a component is removed from the page, like stopping timers or removing event listeners.
Click to reveal answer
beginner
How do you import <code>onDestroy</code> in a Svelte component?
You import it from 'svelte' like this: <code>import { onDestroy } from 'svelte';</code>
Click to reveal answer
intermediate
Show a simple example of using onDestroy to clear an interval timer.
<pre>import { onDestroy } from 'svelte';

const timer = setInterval(() =&gt; {
  console.log('Tick');
}, 1000);

onDestroy(() =&gt; {
  clearInterval(timer);
});</pre>
Click to reveal answer
beginner
When exactly does the onDestroy callback run in the component lifecycle?
It runs right before the component is removed from the DOM, allowing you to clean up resources.
Click to reveal answer
intermediate
Can you register multiple onDestroy callbacks in one component?
Yes, you can call onDestroy multiple times to register several cleanup functions. All will run when the component is destroyed.
Click to reveal answer
What is the main use of onDestroy in Svelte?
ATo run code when the component is removed from the page
BTo initialize component state
CTo handle user input events
DTo style the component
How do you use onDestroy in a Svelte component?
ACall <code>onDestroy()</code> with a callback function
BWrite a function named <code>onDestroy</code> inside the component
CAdd <code>onDestroy</code> attribute to HTML elements
DUse <code>onDestroy</code> as a CSS class
Which of these is a good use case for onDestroy?
AStarting a timer when component loads
BClearing a timer when component unloads
CRendering HTML content
DFetching data from an API
Can you register more than one onDestroy callback in a component?
AOnly if you use a special syntax
BNo, only one callback is allowed
CYes, multiple callbacks can be registered
DOnly if the component is a class
When does the onDestroy callback run?
AAfter the component is added to the DOM
BWhen the component updates
CWhen the component receives props
DBefore the component is removed from the DOM
Explain how and why you would use onDestroy in a Svelte component.
Think about what needs to be cleaned up when a component disappears.
You got /4 concepts.
    Describe a scenario where forgetting to use onDestroy could cause problems in a Svelte app.
    Imagine a timer keeps running even after you leave a page.
    You got /4 concepts.