Bird
Raised Fist0
Svelteframework~5 mins

onDestroy in Svelte - Cheat Sheet & Quick Revision

Choose your learning style10 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.

      Practice

      (1/5)
      1. What is the main purpose of the onDestroy function in a Svelte component?
      easy
      A. To run cleanup code when the component is removed from the page
      B. To initialize component state when it loads
      C. To update the component when data changes
      D. To handle user input events

      Solution

      1. Step 1: Understand the lifecycle of a Svelte component

        The onDestroy function runs when the component is about to be removed from the page.
      2. Step 2: Identify the purpose of onDestroy

        It is used to clean up things like timers or event listeners to avoid bugs or memory leaks.
      3. Final Answer:

        To run cleanup code when the component is removed from the page -> Option A
      4. Quick 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
      A. import { onDestroy } from 'svelte'; onDestroy.cleanup(() => { /* cleanup */ });
      B. import onDestroy from 'svelte'; onDestroy(() => { /* cleanup */ });
      C. import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ });
      D. import { onDestroy } from 'svelte'; onDestroy = () => { /* cleanup */ };

      Solution

      1. Step 1: Check the import syntax

        The correct import is a named import: import { onDestroy } from 'svelte';
      2. Step 2: Check how to use onDestroy

        You call onDestroy with a function to run cleanup code: onDestroy(() => { ... });
      3. Final Answer:

        import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ }); -> Option C
      4. Quick 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:
      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
      A. The interval timer continues running and logs 'Tick' forever
      B. The component reloads automatically
      C. An error occurs because clearInterval is called incorrectly
      D. The interval timer stops and no more 'Tick' logs appear

      Solution

      1. Step 1: Understand the timer setup

        The code sets a repeating timer with setInterval that logs 'Tick' every second.
      2. Step 2: Analyze the onDestroy cleanup

        The onDestroy callback calls clearInterval(timer), which stops the timer when the component is removed.
      3. Final Answer:

        The interval timer stops and no more 'Tick' logs appear -> Option D
      4. Quick 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:
      import { onDestroy } from 'svelte';
      
      function handleClick() {
        console.log('Clicked');
      }
      
      window.addEventListener('click', handleClick);
      
      onDestroy(() => {
        window.removeEventListener('click');
      });

      What is wrong with this code?
      medium
      A. removeEventListener is missing the event handler function argument
      B. onDestroy should be called before addEventListener
      C. handleClick should be defined inside onDestroy
      D. window.addEventListener should be inside onDestroy

      Solution

      1. Step 1: Check removeEventListener usage

        To remove an event listener, you must pass both the event type and the exact handler function.
      2. Step 2: Identify the missing argument

        The code calls window.removeEventListener('click'); without the handler handleClick, so the listener is not removed.
      3. Final Answer:

        removeEventListener is missing the event handler function argument -> Option A
      4. Quick 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
      A. onDestroy(() => { clearInterval(timer); window.removeEventListener('custom'); });
      B. onDestroy(() => { clearInterval(timer); window.removeEventListener('custom', onCustomEvent); });
      C. onDestroy(() => { clearInterval(timer); }); onDestroy(() => { window.removeEventListener('custom'); });
      D. onDestroy(() => { clearInterval(); window.removeEventListener('custom', onCustomEvent); });

      Solution

      1. Step 1: Combine cleanup tasks in one onDestroy callback

        onDestroy accepts a single function where you can clean multiple resources.
      2. Step 2: Correctly clear timer and remove event listener

        Use clearInterval(timer) and window.removeEventListener('custom', onCustomEvent) with proper arguments.
      3. Final Answer:

        onDestroy(() => { clearInterval(timer); window.removeEventListener('custom', onCustomEvent); }); -> Option B
      4. Quick 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 strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard