> For the complete documentation index, see [llms.txt](https://132oq-szjxckld--diwejk1k2j-1123n.gitbook.io/documentation-studio-shento/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://132oq-szjxckld--diwejk1k2j-1123n.gitbook.io/documentation-studio-shento/getting-started-with-sveltekit/base-syntax-and-core-features-of-svelte/using-usdeffect.md).

# 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:

{% tabs %}
{% tab title="src/App.svelte" %}

```html
<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>
```

{% endtab %}

{% tab title="localhost/test.html" %}
Clicks: 0

Click me

Count is now: 1 Count is now: 2 Count is now: 3
{% endtab %}
{% endtabs %}

### 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.

{% tabs %}
{% tab title="src/App.svelte" %}

```html
<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>
```

{% endtab %}

{% tab title="localhost/test.html" %}
Reset

Count: 0

Count: 1 Count: 2 Count: 3

Count: 0
{% endtab %}
{% endtabs %}

## Important Considerations

{% hint style="warning" %}
The `$effect` rune should not be used to compute reactive values. For derived values, use the `$derived` rune instead.
{% endhint %}

## 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**:

```html
<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**:

{% tabs %}
{% tab title="src/App.svelte" %}

```html
<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>
```

{% endtab %}

{% tab title="localhost/test.html" %}
Clicks: 0

Click me

Count is now: 1 Count is now: 2 Count is now: 3
{% endtab %}
{% endtabs %}

## 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.
