Svelte Basics - Reactivity - Part 3

23 Mar, 2022, 5 min read

Svelte Training Course - Free Course

5 part series

Svelte Basics - Reactivity

This post is a continuation of the course on Svelte. If you haven't read the previous parts of the series, we would recommend going through the post in the order.

Previous post -

Before we dive into reactivity, let’s get a few basics things answered to be on the same page.

What is DOM?

DOM is the representation of the content of the HTML document which is present in memory in the browser. Your webpage which you see is made up of multiple HMTL elements that are loaded in memory by the browser. DOM stands for Document Object Model (DOM) which is like a programming interface that is a common standard for web documents.

So javascript used the DOM interface to interact with the web browser. If you want to get a list of elements from the page, you can do it using the doucment.querySelectorAll method which will return a list of elements in a pre-defined format.

For more detailed information about the DOM, Check this website

What is the link between the DOM and Svelte Reactivity? Svelte or any other frontend framework has to work with the DOM in order to manipulate the HTML elements and show the proper data which needs to be shown. Svelte does this using simple javascript which is generated during the build time to interact with the DOM. So when the content changes, Javascript updates the DOM element and you can see the changes on the browser.

What does reactivity mean in Frontend?

Reactivity means changing the HTML in the page when there is an update to the component state. This reactivity will help developers make updates to the app's internal state and let Svelte (Since Svelte is not a runtime, this is handled by javascript technically) do the hard part of syncing the state to the HTML DOM.


How Svelte updates DOM

As you already know by now, We write the components in a svelte file and that gets rendered as an HTML page in the browser. So when the internal state of the variable changes in Svelte, it triggers an update in the browser to only change the elements which need to be updated.

The tricky part is to update the least number of HTML elements on the page to perform the efficient update. Since multiple DOM updates are costly in terms of rendering times, Svelte batches these operations and perform them in an efficient manner. Details of how this works are beyond the scope of these simple explanations and we can cover them in a future post.


In the example screenshot, when the button is clicked, the value of the cart item is updated and then only the <h1> element is updated in the DOM and the rest of the DOM is not updated. This is the most efficient as the changes are only to that particular element. If the same information is displayed in multiple HTML elements, all those elements will be updated.

Defining dependant variables in Svelte

We know that when a variable is assigned a new value, Svelte will update the state and re-render the component on its own. What if you have some dependent variable on the first one and want to stay in sync when the main variable is updated.

	let myFavNums = [5, 12, 55, 81];
	let myFavNumsTotal = 153;

<h1>Fav Total: {myFavNumsTotal}</h1>

In the above example, when the array variable myFavNums changes, myFavNumsTotal is not updated and so you will have an issue. You can use the reactive statement of svelte to update a dependent varaible.

	let myFavNums = [5, 12, 55, 81];
	$: myFavNumsTotal = myFavNums.reduce((a, b) => a + b);


<h1>Fav Total: {myFavNumsTotal}</h1>

Just adding the $: in front of the variable lets svelte know that it needs to recalculate that varaible if one of the dependent variables changes. In this case, the dependent variable is myFavNums

We are using reduce to calculate the total of the array by converting the multiple items into a single value. Don’t worry if you are not sure what reduce function is used. You can learn more about reduce here. You can do any kind of calculation here instead of the reduce function.

	let myFavNums = [5, 12, 55, 81];
	$: myFavNumsTotal = myFavNums.reduce((a, b) => a + b);
	const addFavNum = () => {
		myFavNums = [...myFavNums, 65];

<h1>Fav Total: {myFavNumsTotal}</h1>
<button on:click={() => addFavNum()}>Add Item</button>

Dependent variables in svelte Repl

This is a more complete example that demonstrates how updating the array will result in the myFavNumsTotal being recalculated. If you are not sure why we are using the ... spread operator here check the previous post here where we discussed how to update the array in Svelte

Adding reactive statement in Svelte

Similar to variables being reactive, you can also have statements that are reactive in Svelte. You just have to use the $: syntax before the statement to make it reactive. You can have more than one statement using the {} blocks.

$: console.log('Updated: ' + myFavNums);

These can be useful if you want to run some functions when the value of a variable is updated like below

let income = 10000;
$: {

Reactive statement REPL in Svelte

About the Author

Sriram Thiagarajan

Sriram is a content creator focused on providing quality content which provides value for the readers. He believe is constant learning and sharing those learning with the group. He is working as a lead developer and bulk of his experience is in working with multiple javascript frameworks such as Angular, React, Svelte. He is passionate about open source technologies and on his free time loves to develop games.

Join our mailing list

We will reach out when exciting new posts are available. We won’t send you spam. Unsubscribe at any time.