Using $effect

If you want to run a function after the component mounts and rerun it whenever specific reactive values (like $state or $derived) change, you should use $effect in Svelte 5.

Understanding the $effect Rune in Svelte 5

Svelte 5 introduces a new system for handling reactivity called runes. Among these, the $effect rune is a powerful tool for managing side effects in your Svelte applications. Let's dive into what $effect is, how it works, and how to use it effectively.

What is $effect?

The $effect rune allows you to perform actions in response to changes in reactive variables. It is similar to the useEffect hook in React but is designed to be simpler and more intuitive. The $effect rune runs after the DOM has been updated, making it ideal for tasks like logging, fetching data, or manipulating the DOM directly.

Basic Usage

Here is a basic example of how to use the $effect rune:

<script>
  import { $state, $effect } from 'svelte';

  let count = $state(0);

  // Effect to log the count whenever it changes
  $effect(() => {
    console.log(`Count is now: ${count}`);
  });

  function increment() {
    count += 1;
  }
</script>

<button on:click={increment}>
  Clicks: {count}
</button>

Key Points

  • Reactive Variables: In the example, count is a reactive variable created using $state.

  • Effect Function: The function inside $effect runs every time count changes.

  • DOM Update: The effect runs after the DOM has been updated.

Advanced Usage

The $effect rune can also be used for more complex tasks. For instance, you can perform cleanup actions by returning a function from the $effect callback.

<script>
  import { $state, $effect } from 'svelte';

  let count = $state(0);

  // Effect with cleanup
  $effect(() => {
    const interval = setInterval(() => {
      count += 1;
    }, 1000);

    // Cleanup function
    return () => {
      clearInterval(interval);
    };
  });

  function reset() {
    count = 0;
  }
</script>

<button on:click={reset}>
  Reset
</button>
<p>Count: {count}</p>

Important Considerations

Comparison with Previous Svelte Versions

In Svelte 4, you would use the $: label for reactive statements and side effects. The $effect rune in Svelte 5 provides a clearer and more modular way to handle side effects.

Svelte 4 Example:

<script>
  export let count = 0;

  // Reactive statement
  $: console.log(`Count is now: ${count}`);
</script>

<button on:click={() => count += 1}>
  Clicks: {count}
</button>

Svelte 5 Equivalent:

<script>
  import { $state, $effect } from 'svelte';

  let count = $state(0);

  $effect(() => {
    console.log(`Count is now: ${count}`);
  });

  function increment() {
    count += 1;
  }
</script>

<button on:click={increment}>
  Clicks: {count}
</button>

Conclusion

The $effect rune in Svelte 5 offers a powerful and flexible way to handle side effects in your applications. By understanding and using $effect effectively, you can create more maintainable and efficient Svelte components.

Last updated