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>My name is Shento
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>My name is SHENTO
Explanation
Let's break down the code:
Reactive State Declaration:
let name = $state('Shento');Here,
nameis 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());uppercaseNameis a derived state that depends onname. It automatically updates to the uppercase version ofnamewhenevernamechanges. The.toUpperCase()method is standard JavaScript.HTML Binding:
<h1>My name is {uppercaseName}</h1>This line binds the
uppercaseNamevariable 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
$stateto declare reactive state variables.Use
$derivedto 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