Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Use reactive declarations to compute component state in Svelte 3

    Tomasz ŁakomyTomasz Łakomy
    sveltesvelte

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    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.