Documentation Shento Hendriks
Svelte / SvelteKit
Svelte / SvelteKit
  • Getting Started with SvelteKit
    • Installing SvelteKit
      • Tailwind Typography plugin
    • Base Syntax & Core Features of Svelte
      • Curly Braces & Understanding Core Syntax
      • Reactive Variables
      • Two-way-binding Shortcut
      • Using multiple components
      • Components & Communication via Props
      • Display HTML in Svelte
      • Dynamic classes
      • Using $effect
      • Working with Javascript and Rune reactivity
    • Working with Conditionals & Loops
      • Showing code conditionally in Svelte
      • Looping through arrays (lists)
      • Lists & Keys
    • Closer look at reactivity
      • Updating Arrays & Objects
      • Event Modifiers
    • Component Events
    • Best Practices
    • Adding Google Font in Tailwind and SvelteKit
    • Adding Local Fonts to SvelteKit with Tailwind
    • Prevent flicker in images
    • Enhanced Images
    • Form Submissions in SvelteKit
    • Effective SEO in SvelteKit
    • Automatic Site Maps in Svelte
    • Creating Custom Elements with Svelte, SvelteKit, and Vite
    • Creating a Svelte Library with JavaScript Functions
  • Useful Code Snippets
    • Hover effects
    • Navigation
    • Centering Items
    • Setting Footer Bottom Page
  • Installing Useful Libraries
    • Documenting Javascript with JSDocs (Crash Course)
    • Adding Lottie Animations to Svelte Application
    • SvelteKit Melt-ui
      • First Component - accordion
    • Installing Shadcn/ui Svelte
    • Getting Started with GSAP with SvelteKit
      • What is GSAP?
      • Installing GSAP & Your first animation
      • GSAP in SvelteKit
    • Installing Locomotive Scroll with Svelte 5 and SvelteKit
  • SvelteKit Server Fetching and Deployment
    • Preparing a SvelteKit application for Deployment
    • Utility Functions for URL Handling in SvelteKit
    • Fetching Directus Data from Rest API with SvelteKit
    • Fetching data from api with caching
    • Displaying Fetched Data in a Each Loop
    • Creating slug friendly urls based on query data
    • Finding correct query in api based on url slug
Powered by GitBook
On this page
  • Understanding the $effect Rune in Svelte 5
  • What is $effect?
  • Basic Usage
  • Key Points
  • Advanced Usage
  • Important Considerations
  • Comparison with Previous Svelte Versions
  • Svelte 4 Example:
  • Svelte 5 Equivalent:
  • Conclusion
  1. Getting Started with SvelteKit
  2. Base Syntax & Core Features of Svelte

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>

Clicks: 0

Click me

Count is now: 1 Count is now: 2 Count is now: 3

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>

Reset

Count: 0

Count: 1 Count: 2 Count: 3

Count: 0

Important Considerations

The $effect rune should not be used to compute reactive values. For derived values, use the $derived rune instead.

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>

Clicks: 0

Click me

Count is now: 1 Count is now: 2 Count is now: 3

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.

PreviousDynamic classesNextWorking with Javascript and Rune reactivity

Last updated 9 months ago