DEV Community

loading...

Reactive Variables are the BEST feature in Svelte

datsgabs profile image Gabriel Lazcano ・1 min read

Link to original article with code snippets (recommended): https://gabriellazcano.com/blog/reactive-variables-are-the-best-feature-in-svelte/

Well, maybe I’m exagerating a little bit. But for real, reactive variable are such a good feature I don’t know how other frameworks haven’t copied it to it’s full extent yet.

They work like this, you declare a variable and if the variable changes it triggers another variable to change it’s value if it’s related to the initial variable.

You can see a similar example in the docs . But what this basically does, is that every time we change the value of the input it would change the double variable to be times 2 the a variable.

And you could do lots of things with it.

Changing the document title.

And even calling functions. For this I have the perfect example, making an svg triangle with the sides being reactive. And also using the reactive variables feature to get the hypotenuse with a neat one liner

https://codesandbox.io/s/brave-einstein-2hfx4

Thanks for reading. If you’ve got any other example of how reactive variables could be used feel free to let me know :))

Discussion (1)

pic
Editor guide
Collapse
jesperhoy profile image
Jesper Høy

I really like this feature too - including the nice terse $: syntax.

Vue.js does have something very similar in the "computed" (see vuejs.org/v2/api/#computed) and "watch" (see vuejs.org/v2/api/#watch) options.