How to properly handle cleanup in Svelte 5 with $effect? #17592
-
|
Hi everyone! 👋 I'm migrating my project from Svelte 4 to Svelte 5 and I'm a bit confused about how to handle cleanup functions with the new In Svelte 4, I used <script>
import { onDestroy } from 'svelte';
let interval = setInterval(() => {
console.log('tick');
}, 1000);
onDestroy(() => {
clearInterval(interval);
});
</script>How should I write this in Svelte 5 using <script>
$effect(() => {
const interval = setInterval(() => {
console.log('tick');
}, 1000);
return () => {
clearInterval(interval);
};
});
</script>Is this the right way? Are there any best practices I should follow? Thanks in advance! 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Yes, your approach is correct! 🎉 In Svelte 5,
Your code is the right way to do it: <script>
$effect(() => {
const interval = setInterval(() => {
console.log('tick');
}, 1000);
// Cleanup function
return () => {
clearInterval(interval);
};
});
</script>Key points:
<script>
let count = $state(0);
$effect(() => {
console.log(`Count is now: ${count}`);
return () => {
console.log(`Cleaning up for count: ${count}`);
};
});
</script>When to still use
|
Beta Was this translation helpful? Give feedback.
Yes, your approach is correct! 🎉
In Svelte 5,
$effectsupports returning a cleanup function that runs when:Your code is the right way to do it:
Key points:
Return a function from
$effectfor cleanup — this replacesonDestroyfor most casesThe cleanup runs automatically when the component unmounts or before the effect re-runs
If you need reactive dependencies, they're tracked automatically: