[Svelet Tutorial] 2. Reactivity

2. Reactivity

At the heart of Svelte is a powerful system of reactivity for keeping the DOM in sync with your application state.

a. Assignments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
let count = 0;

function incrementCount() {
// event handler code goes here

// Inside the incrementCount function, all we need to do is change the value of count:
// Svelte 'instruments' this assignment with some code that tells it the DOM will need to be updated.
count += 1;
}
</script>

<button on:click={incrementCount}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

b. Declarations

Svelte automatically updates the DOM when your component’s state changes. Often, some parts of a component’s state need to be computed from other parts (such as a fullname derived from a firstname and a lastname), and recomputed whenever they change.

For these, we have reactive declarations. They look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
let count = 0;
$: doubled = count * 2;

function handleClick() {
count += 1;
}
</script>

<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

<p>{count} doubled is {doubled}</p>

Of course, you could just write {count * 2} in the markup instead — you don’t have to use reactive values. Reactive values become particularly valuable when you need to reference them multiple times, or you have values that depend on other reactive values.

References

[1] Reactivity / Assignments • Svelte Tutorial - https://svelte.dev/tutorial/reactive-assignments

[2] Svelte • Cybernetically enhanced web apps - https://svelte.dev/

[3] API Docs • Svelte - https://svelte.dev/docs