Svelte - Reactive Statements

Svelte - Reactive Statements

ยท

2 min read

The Reactive Statement is used when a variable depend on another value or when you want to trigger an action after one of these values changes.

How

The syntax is quite simple, you just need to put $sign into the script tag. The rest of this statement is just write a variable or value that you want to watch.

Let's say while the user logout, we want to show notification. Hence you can write the syntax like this...

let isUserActive = true; // The user is online

$: if (!isUserActive) console.log("the user has logged out!");

With the following code, you will be able to tell the browsers, whenever the value of isUserActive turn into false, then browsers should display the notification that the user has been logged out.

Different Behaviour

That is the behaviour when you watch data type between primitive type like boolean or string or number. Svelte will update that value only one time since the value has been changed. Otherwise, if the value doesn't change anymore, Svelte will keep it up and not triggered.

But what if that is an objects which could have several different data type inside it, will the behaviour be different? Well, to answer this question, we have to look at the code below...

<button on:click={authenticateTheUser}>Authenticate</button>
let isUserAuthenticate = false; // Primitive type
let isUser = { authenticate: false }; // Object type

// This primitive will be updated once
$: if (isUserAuthenticate) 
  console.log("user is authenticated");

// This object will be updated every time the button is clicked
$: if (isUser.authenticate)
  console.log("user is authenticated inside this object");

function authenticateTheUser() {
  isUserAuthenticate = true;
  isUser.authenticate = true;
}

As you can see, if that is an type of object, then Svelte will automatically re-updating even though the value has been the same.

The only reason as cdellacqua on github said, "because the reactive statement gets triggered if any of the values an object contains changes."

Conclusion

Reactive Statements will be very useful as long as you know how to use it! ๐Ÿ™‚

ย