Reactivity
Share:
Before diving into the code, let's get an understanding of Svelte's reactivity concepts and how it differs from other JavaScript frameworks. Svelte's reactivity is rather straightforward — when data changes, the changes get reflected in the UI immediately. There's no need to write extra code for tracking changes or update the DOM manually. Every ‘reactive statement’ in Svelte gets called whenever the state of our app changes. This simplistic yet powerful model makes Svelte highly appealing for modern web development.
Now, let's take an example from the world of movies for understanding Svelte's reactivity. Suppose we have a movie character, say 'Luke Skywalker', and a feature associated with it, like 'strength'. With Svelte, we can easily build a piece of UI to reflect changes in Luke's strength level. We'll use 'strengthValue' to represent Luke's power.
First, we'll declare the initial strengthValue:
let strengthValue = 100;
And then in the HTML part of our script, we'll display this value:
<h2>Luke Skywalker's strength: {strengthValue}</h2>
This will show the current strength value of Luke Skywalker on our webpage.
Now, let's bring reactivity into play here. Suppose Luke Skywalker fights Darth Vader and his strength gets depleted. In Svelte, changes can be made reactive using the '$:' syntax. Let's demonstrate:
let strengthValue = 100;
function fightVader() {
strengthValue = strengthValue - 40;
}
$: currentStrength = `Luke Skywalker's strength: ${strengthValue}`;
In the HTML section, we'll bind the function to a button and display strengthValue:
<h2>{currentStrength}</h2>
<button on:click={fightVader}>Fight Vader</button>
Here, whenever fightVader()
is called, strengthValue
changes and because its change is observed in a reactive statement, currentStrength
is automatically updated in the DOM.
Svelte also supports Reactive Declarations which are a type of reactive statement. This refers to statements that get re-run whenever their state changes (or the state of their dependencies). Let's see this with an example:
let forceLevel = 50;
let strengthValue = 100;
$: totalPower = forceLevel + strengthValue;
In the above example, totalPower
gets recalculated whenever forceLevel
or strengthValue
changes.
Moreover, Svelte allows conditional reactivity. This form of reactivity helps us create statements that change based on specific conditions. Let's see this in action with our movie scenario. Suppose if the combined total strength and force-level falls below 70, we declare Luke Skywalker defeated:
$: {
if (totalPower < 70) {
console.log("Luke Skywalker is defeated");
}
}
Here, the statement runs whenever there's a change in the reactive dependency, i.e., totalPower
.
Lastly, Svelte supports reactive statements with async-await! Suppose Luke Skywalker needs to recover his strength and forceLevel after being defeated. When this happens, we can asynchronously update the values as follows:
async function recover() {
await Promise.resolve('Recovering...');
strengthValue = 100;
forceLevel = 50;
}
Now when we call recover()
, the promise is awaited first, and then strengthValue
and forceLevel
are updated, marking an end to the reactive statement.
That brings to a close our understanding of Svelte's reactivity concepts. Svelte's reactivity is clean and concise, only updating what needs updating when values change. This model leads to less code and faster updates, making Svelte a favorite among developers. In the world of increasingly complex front-end applications, having a framework that lets you manage state changes gracefully and quickly can be invaluable.
0 Comment
Sign up or Log in to leave a comment