Reactive Variables

Guide to Reactive State in Svelte

Svelte is a modern JavaScript framework that makes it easy to build reactive web applications. One of its powerful features is the ability to declare reactive state and derived state. This guide will walk you through how to use these features effectively.

Basic Reactive State

In Svelte, you can declare a piece of reactive state using the $state rune. This allows your application to automatically update when the state changes.

Example Code

Here is a minimal example of declaring and using reactive state in Svelte:

<script>
    let name = $state('Shento');
</script>

<h1>My name is {name}</h1>

Derived State

If a value depends on another value, you can use the $derived rune. This ensures that the derived value is automatically recalculated whenever the dependent value changes.

Example Code

Let's extend our previous example to include a derived state:

<script>
    let name = $state('Shento');
    let uppercaseName = $derived(name.toUpperCase());
</script>

<h1>My name is {uppercaseName}</h1>

Explanation

Let's break down the code:

  • Reactive State Declaration:

    let name = $state('Shento');

    Here, name is a reactive state variable initialized with the value 'Shento'. You can name this variable anything you like.

  • Derived State Declaration:

    let uppercaseName = $derived(name.toUpperCase());

    uppercaseName is a derived state that depends on name. It automatically updates to the uppercase version of name whenever name changes. The .toUpperCase() method is standard JavaScript.

  • HTML Binding:

    <h1>My name is {uppercaseName}</h1>

    This line binds the uppercaseName variable to the HTML, so it displays the current value of uppercaseName.

Important Points

The $state and $derived runes are specific to Svelte and are used to create reactive and derived state variables.

Summary

  • Use $state to declare reactive state variables.

  • Use $derived to declare variables that depend on other reactive state variables.

  • Bind these variables to your HTML to automatically update the UI when the state changes.

Last updated