November 16, 2024

Svelte 5 - How to Use Runes

Want to improve your Svelte 5 apps? Runes can help! They make your app more interactive and are easy to use. With runes, managing state and reactivity in Svelte is simpler and more effective. Let’s see how runes can enhance your Svelte 5 project.

What are runes?

In Svelte 5, runes help control how your app reacts to changes. They make handling state in components easier. The main runes are $state, $derived, and $effect.

Understanding runes

Here are the basic runes that make Svelte 5 reactivity work:

  • $state: Creates reactive variables that automatically update when they change, making things easier for you.

    <script>
      let count = $state(0);
    </script>
    
    <button onclick={() => count++}>
      Clicks: {count}
    </button>

    In this example, we create a reactive variable count initialized to 0. Whenever the button is clicked, count increments, and the displayed value updates automatically.

  • $derived: Creates values from $state or other $derived values that automatically recalculate when needed.

    <script>
      let count = $state(0);
      const doubled = $derived(count * 2);
    </script>
    
    <p>Click count: {count}</p>
    <p>Click doubled: {doubled}</p>

    Here, doubled is a derived variable that automatically recalculates its value based on count. When count changes, doubled updates to be twice the count.

  • $effect: Runs specific code when the state inside it changes, like updating the UI or working with other libraries. Use it to keep your code clean.

    <script>
      let count = $state(0);
    
      $effect(() => {
        console.log(`Count changed to ${count}`);
      });
    </script>
    
    <button onclick={() => count++}>
      Clicks: {count}
    </button>

    This example demonstrates $effect, which logs a message to the console each time the count variable changes, showing reactivity in action.

  • $props: Allows components to receive and handle properties effectively, ensuring incoming values are managed reactively, similar to handling component state.

    <!-- Parent component -->
    <Counter value={10} />
    
    <!-- Counter.svelte -->
    <script>
      const { value } = $props();
    </script>
    
    <p>Value is: {value}</p>

    In this case, $props lets a child component receive properties from its parent. value can be used reactively within the child component, illustrating property reactivity.

Final Thoughts

Using runes in Svelte 5 improves your app structure and speeds up development by managing reactivity and reusing code efficiently. Try runes and see how they bring everything together in your Svelte projects. Happy coding!