DEV Community

Cover image for Understanding Svelte Reactivity 
Mrityunjay-Palled
Mrityunjay-Palled

Posted on

Understanding Svelte Reactivity 

Reactivity is one of the most important and useful features of Svelte. It helps to keep the DOM in sync with the application state. Now let's take a look at the example.

Image description

As we see above, we are not using any state variables like we do in React to update the application state. In our example, whenever the value of count changes, Svelte reacts automatically and updates the application state, and keeps our application state in sync with the DOM. Svelte uses something called a "reactive declaration" to keep variables also in sync with each other. Let's understand with an example.

Image description

In the above example as we can see doubledCount is referring to the count variable whenever the value of count is doubled Svelte automatically re-renders the entire code again to update the value of doubledCount. In this way we can keep variables in sync with each other. In Svelte, any changes made to an array or object do not cause components to re-render on their own. Let's try to understand with an example.

Image description

Image description

In the above example, we are trying to push a random number between 1 and 10 into an array when the button is clicked. In the above case, no matter how many times we click the button, it does not cause a component to re-render, as Svelte on its own does not react to any changes that happens to arrays or objects. We can solve the above problem manually by causing a component to re-render. This can be done as shown below.

Image description

Image description

As we see above, we are causing a component to manually re-render
by assigning a variable to itself. As we know in Svelte assignment always causes a component to re-render. In this way, we are indirectly making this component react to any changes that happen to the array. Now, for every button click, a new random number will be displayed on the screen.

Top comments (0)