0
0
Svelteframework~10 mins

onDestroy in Svelte - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - onDestroy
Component Mounts
Setup onDestroy callback
Component Active
Component Unmounts
onDestroy callback runs
Cleanup done
This flow shows how Svelte runs the onDestroy callback when a component is removed from the page to clean up resources.
Execution Sample
Svelte
import { onDestroy } from 'svelte';

onDestroy(() => {
  console.log('Cleanup running');
});
This code sets up a cleanup function that runs when the component is removed from the page.
Execution Table
StepActionCallback RegisteredComponent StateConsole Output
1Component mountsonDestroy callback setActive
2Component stays activeonDestroy callback setActive
3Component unmountsonDestroy callback triggeredUnmountingCleanup running
4Cleanup completeNo callback pendingDestroyed
💡 Component unmount triggers onDestroy callback, then cleanup finishes.
Variable Tracker
VariableStartAfter MountAfter UnmountFinal
componentStateundefinedActiveUnmountingDestroyed
onDestroyCallbackundefinedRegisteredTriggeredNone
Key Moments - 2 Insights
Why does the onDestroy callback run only when the component unmounts?
Because onDestroy is designed to clean up resources when the component is removed, as shown in execution_table step 3 where the callback triggers only on unmount.
Can onDestroy run multiple times during the component lifecycle?
No, onDestroy runs once when the component unmounts, as the callback is triggered only at that moment (execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the componentState at step 2?
AActive
BUnmounting
CDestroyed
DUndefined
💡 Hint
Check the 'Component State' column at step 2 in the execution_table.
At which step does the console output 'Cleanup running' appear?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Console Output' column in the execution_table.
If the component never unmounts, what happens to the onDestroy callback?
AIt runs repeatedly
BIt runs immediately after mount
CIt never runs
DIt runs after a delay
💡 Hint
Refer to the execution_table where the callback triggers only at unmount (step 3).
Concept Snapshot
onDestroy(callback) registers a cleanup function.
Runs once when component unmounts.
Use it to free resources like timers or subscriptions.
No repeated calls; only on removal.
Helps keep app efficient and bug-free.
Full Transcript
In Svelte, the onDestroy function lets you run code when a component is removed from the page. First, the component mounts and the onDestroy callback is registered. While the component is active, the callback waits silently. When the component unmounts, Svelte runs the onDestroy callback to clean up resources like timers or event listeners. This happens only once per component lifecycle. This process helps keep your app clean and efficient by freeing resources no longer needed.