Skip to content
Discussion options

You must be logged in to vote

Yes, your approach is correct! 🎉

In Svelte 5, $effect supports returning a cleanup function that runs when:

  • The component is destroyed
  • The effect re-runs (dependencies change)

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:

  1. Return a function from $effect for cleanup — this replaces onDestroy for most cases

  2. The cleanup runs automatically when the component unmounts or before the effect re-runs

  3. If you need reactive dependencies, they're tracked automatically:

<script>
  let

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@kingpig0117
Comment options

Answer selected by kingpig0117
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants