Reactive Side Effects with `$effect`
Introduction to Reactive Side Effects
Welcome to the first lesson of the course Svelte: Reactivity & State Management! In this lesson, we’ll dive into one of the most powerful features of Svelte: reactive side effects. Reactive side effects are actions that happen automatically when your application’s state changes. For example, if you’re building a countdown timer, you might want to update the timer every second. This is where the $effect rune comes in. It allows you to manage these side effects in a clean and efficient way.
Think of $effect as a way to say, “Whenever this value changes, do this.” It’s like setting up a watchman who keeps an eye on specific data and takes action when it changes. In this lesson, we’ll use $effect to build a countdown timer, and you’ll learn how to handle side effects like timers, event listeners, and more.
By the end of this lesson, you’ll understand how to use $effect to manage side effects and ensure your application runs smoothly. Let’s get started!
Understanding the `$effect` Rune
Using `$effect` for Cleanup
When using $effect, it’s important to clean up after yourself to avoid memory leaks or unexpected behavior. For example, if you set up a timer using setInterval, you should clear it when it’s no longer needed. Here’s how you can do that:
In this example, the $effect rune sets up a timer that counts down from 10. When the timer is no longer needed (e.g., when the user clicks “Stop”), the cleanup function (clearInterval) is called to stop the timer. This ensures that your application doesn’t waste resources or behave unexpectedly.
Cleanup is a crucial part of using $effect, and it’s something you’ll need to consider whenever you’re managing side effects. In the next section, we’ll explore how to use the untrack function to avoid unnecessary re-runs.

