Reactive Side Effects with `$effect`

Introduction to Reactive Side Effects

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:

Svelte
<script>
    let timeLeft = $state(10);
    let running = $state(false);

    $effect(() => {
        if (!running) return;

        const id = setInterval(() => {
            if (timeLeft > 0) {
                timeLeft -= 1;
            } else {
                running = false;
            }
        }, 1000);

        return () => {
            clearInterval(id); // Cleanup the interval
        };
    });
</script>

<button onclick={() => running = true}>Start</button>
<button onclick={() => running = false}>Stop</button>
<p>Time left: {timeLeft}</p>

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.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal