Svelte - Advance Reactivity



Advanced reactivity in Svelte allows developers to optimize their applications by using raw state, reactive classes, reactive built-ins, stores, getters, and setters. In this chapter we will see how to implement advanced reactivity while covering all important concepts for this.

Defining Raw State

Raw state allows you to handle data without using Svelte's automatic updates. This is especially useful for data that you won't keep for a long time after it's created.

Syntax

To declare a raw state variable, you use the $state.raw() function:

let myArray = $state.raw([]);

Reactive Classes

In Svelte, not only can you make variables reactive, but you can also make properties of classes reactive. This means that when you change a property, the UI will automatically update to reflect those changes.

Syntax

In Svelte, you can create a reactive class by using the $: syntax to make the class properties reactive as shown below:

export class Counter {
    count = $state(0); // Reactive property

    increment() {
        this.count += 1; // Increment the count
    }
}

Getters and Setters

Getters and Setters also known as accessors in svelte. Getters and setters allow to you create custom actions that will be used when you access or change a property in a class. They help manage how properties are used, making it easier to apply rules or checks.

Defining Getters and Setters

Getters and setters can be defined effectively using the following steps:

  • Create a Class: The first thing to do is define a class where you want to use getters and setters.
  • Define a Private Variable: Next, have to create a private properties using # symbol.
class className{
        #propertyName= $state(0);
    }
  • Define a Getter: You can create a getter for a property by using "get" keyword followed by the name of the property.
  • get propertyName() {
            return this.#propertyName;
        }
  • Define a Setter: Now you can define a setters using the set keyword.
  • set propertyName(value) {
            this.#propertyName= value;
        }

    Reactive Built-ins

    Svelte provides various reactive built-ins of regular JavaScript objects that react to changes. This means that if you change something in these objects, the user interface will automatically update to reflect those changes.

    Examples of Reactive Built-ins

    The reactive built-ins include:

    • SvelteMap: A reactive version of the JavaScript Map.
    • SvelteSet: A reactive version of the JavaScript Set.
    • SvelteDate: A reactive version of the JavaScript Date.
    • SvelteURL: A reactive version of the JavaScript URL.
    • SvelteURLSearchParams: A reactive version of the JavaScript URLSearchParams.

    Stores

    Svelte stores help you manage and share data between different parts of the Svelte app. They allow you to keep track of information that multiple components can use and update.

    One of the types of store is a writable store. It allows you to change and update its value. You can create a writable store by using the writable function from the svelte/store module.

    Defining Writable Stores

    A writable store can be created using a writable function as shown below:

    import { writable } from 'svelte/store';
    const count = writable(0); // Initializes the store with a value of 0

    Accessing Store Values

    To get the value of a store, you use the $ sign in front of its name. For example, if your store is called count, you can access its value by using $count.

    Updating Store Values

    To change the value of a writable store, you can use its set or update methods. In a component, you can also change the store's value directly by using the $ sign in front of it. For example:

    $count += 1; // Increments the count by 1

    Example

    This example will demonstrate how to create a writable store, update its value, and use it in a Svelte component.

    <!--src/store.js-->
    import { writable } from 'svelte/store';
    
    // Create a writable store with an initial value of 0
    export const count = writable(0); 
    
    <!-- src/Counter.svelte -->
    <script>
        import { count } from './store.js';
    
        // Function to increment the count
        function increment() {
        count.update(n => n + 1);
        }
    
        // Function to decrement the count
        function decrement() {
        count.update(n => n - 1);
        }
    </script>
    
    <h1>Count: {$count}</h1>
    <button on:click={increment}>Increment</button>
    <button on:click={decrement}>Decrement</button>
    
    <!-- src/App.svelte -->
    <script>
        import Counter from './Counter.svelte';
    </script>
    
    <main>
        <h1>Simple Counter App</h1>
        <Counter />
    </main>

    Output

    svelte-stores
    Advertisements