0
0
Svelteframework~3 mins

Why onDestroy in Svelte? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could clean up after itself perfectly every time you leave a page?

The Scenario

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.

The Problem

Without cleaning up, timers keep running, event listeners stay active, and memory fills up. This makes your app slow and buggy over time.

The Solution

The onDestroy function in Svelte lets you run cleanup code automatically when a component is removed, keeping your app fast and error-free.

Before vs After
Before
const timer = setInterval(() => { console.log('tick'); }); // but no clearInterval when done
After
import { onDestroy } from 'svelte';
const timer = setInterval(() => { console.log('tick'); }, 1000);
onDestroy(() => clearInterval(timer));
What It Enables

You can safely create temporary effects or listeners that clean themselves up, making your app smooth and reliable.

Real Life Example

When showing a live chat widget, onDestroy stops the message polling when the chat closes, saving resources.

Key Takeaways

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.