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:
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:
Explanation
Let's break down the code:
Reactive State Declaration:
Here,
name
is a reactive state variable initialized with the value 'Shento'. You can name this variable anything you like.Derived State Declaration:
uppercaseName
is a derived state that depends onname
. It automatically updates to the uppercase version ofname
whenevername
changes. The.toUpperCase()
method is standard JavaScript.HTML Binding:
This line binds the
uppercaseName
variable to the HTML, so it displays the current value ofuppercaseName
.
Important Points
Make sure to always use the $derived
rune for values that depend on other reactive state variables to ensure they update correctly.
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