Use reactive declarations to compute component state in Svelte 3

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

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. This is where reactive declarations come in.

In this lesson we are going to learn how to use reactive declarations to re-compute (and render) square of a counter value in a simple counter example whenever user clicks on a button.

Instructor: [0:00] We have an example of a simple counter app. Basically, whenever I click the button, the handleClick handler is going to trigger, and I am going to increment the current value by 1. We can see the result over here. If I click on the button, we're going to see the counter updated.

[0:13] We would like to be able to create a squared value. Basically, whenever the count is updated, I'd like to have the squared value to be equal to the square of the count current value.

[0:25] We'd like to be able to display it in the DOM like this. The square of the counter is squared, like this. In order to achieve this effect, Svelte has a concept of reactive declarations. In order to create a reactive declaration, we need to use a $ and squared is going to be equal to the count squared, like this.

[0:46] This might be a bit unfamiliar, but this is actually a JavaScript. Right now, if I click on the counter, we're going to see that the counter updates and the square of 10 is exactly 100. Square of 11 is of course 121.

[1:00] Right now, we have the desired effect. We can also have reactive declarations based off other reactive declarations. If I were to do squared - 1 and to have it equal to squared - 1, I can do it like this. Let me just go ahead and display that.

[1:15] Square of the counter - 1 is squared - 1. After I saved, we're going to see the result over here. Right now, the square of the counter is 36 and the square of the counter - 1 is 35.

Hakan Karaduman
Hakan Karaduman
~ 5 years ago

Hi Tomasz,

Those are very informative lessons, thank you for your effort.

I'm confused on how $: is regular javascript, can you explain it more please?

Markdown supported.
Become a member to join the discussionEnroll Today