Published: May 8, 2024
You can see how much I love Svelte and SvelteKit by the sheer number of posts I have about this framework on my website. When Svelte is compared with other frameworks on the internet, it is - injustifiably - mentioned as lacking community support as it is relatively new compared to other established ones like React and Angular.
Therefore, I deem it as my duty to this wonderful framework to enlarge its community and to share my knowledge gained over countless trials and erros with newcomers.
In this post, let's cover reactivity in Svelte.
There are times where a change in a variable does not trigger a change in DOM, and there is some ambiguity about how Svelte does its reactivity. So let's dive in.
Imagine you have below setting where user name needs to be reflected like below:
You can achieved this eacilty in Svelte with binding.
Value of the input can be bound to the name variable like below, and this will ensure that DOM element is always in sync with the input value.
<script>
let name = 'Kepler';
</script>
<input bind:value={name} />
<h1>Welcome {name}</h1>
Let's see whether it works as expected:
It does! Although this is most elegant way to achieve reactivity in Svelte, let's explore other options to get a full understanding on the topic.
Another way to achieve this is with value assignment.
When a variable is assigned a value in script section, it becomes reactive. Binding effect can be achieved, although not elegantly, through value assignment.
<script>
let name = 'Copernicus';
</script>
<input on:change={(e) => (name = e.currentTarget.value)} value={name}/>
<h1>Welcome {name}</h1>
Above code works in below fashion: When value of input changes, it triggers a change event. Once the event is triggered, the name variable is assigned to the value of that input. Since we declared name in script section, it is reactive. Hence, any change in that varibale will trigger re-render of the relevant DOM element. Let's see whether it works as expected:
You will see that the reactivity only kicks in when you fully type in. We don't see reactivity as you type. For this, the change event should be changed to the input event:
<script>
let name = 'Newton';
</script>
<input on:input={(e) => (name = e.currentTarget.value)} value={name}/>
<h1>Welcome {name}</h1>
With above code, reactivity-as-typing can be achieved:
So far we learned that if a veriable is declared within the script tags, it will be reactive. Ie the changes in its value will be reflected in the DOM.
However, there is always an exception to the rule.
If a varible is declared as a derivation from another variable, it won't be reactive even if it is declared within the script tag, nor the value it was derived from is reactive. Let's see this in action below:
<script>
let name = 'Einstein';
let welcomeMessage = `Hello ${name}`;
</script>
<input bind:value={name} />
<h1>{wolcomeMessage}</h1>
In above code, the variable name is reactive as usual. However, we are deriving a new varibale from it called the welcomeMessage.
Let's see whether this will work:
As mentioned above, reactivity won't work here and welcomeMessage is stuck at "Welcome Einstein" even when we change the input. This is because the area between script tags is only run once when the component is rendered. So, welcomeMessage is initialized as "Welcome Einstein" and lets go of all of its attachment to the variable name after the initial render.
In complex apps, we are sure to have derived variables, so how can we make those variables reactive?
By adding a $ (dollar) sign in font of the derived varible, it is possible to make it reactive. This way, svelte will track this variable, and whenever it changes, the change will be reflected in the DOM.
This is achieved as below:
<script>
let name = 'Stephen';
$: welcomeMessage = `Hello ${name}`;
</script>
<input bind:value={name} />
<h1>{wolcomeMessage}</h1>
Let's see whether it will work:
It does! So whenever you have a varible that is derived from another variable, make sure to use the $ (dollar) sign to make it reactive. If you don't like this syntax, there is yet another way to achieve reactivity.
By adding the section that you'd like to make reactive within key tags, you can achieve reactivity without the $ (dollar) sign. The syntax is like below.
<script>
let name = 'Carl';
let welcomeMessage = `Hello ${name}`;
</script>
<input bind:value={name} />
{#key name}
<h1>{wolcomeMessage}</h1>
{/key}
The variable written next to key is the variable you are asking svelte to track. In this case we tell it to track name variable. However, you can also ask it to track welcomeMessage and this should work fine.
In this post, we explored reactivity in svelte. Main topics covered are
Moreover, we learned that derived variables are not tracked in svelte and changes to them won't be reflected in DOM. We explored 2 ways to make these variables reactive:
Svelte is the greatest front-end framework, and its on-the-fly reactivity is one of the main reasons why it is such a wonderful framework. Hope I was able to deepen your understanding of reactivity in Svelte with this post.
Let me know in case of any questions.
Happy hacking!
Leave comment
Comments
Check out other blog posts
2024/06/19
Create A Simple and Dynamic Tooltip With Svelte and JavaScript
2024/06/17
Create an Interactive Map of Tokyo with JavaScript
2024/06/14
How to Easily Fix Japanese Character Issue in Matplotlib
2024/06/13
Book Review | Talking to Strangers: What We Should Know about the People We Don't Know by Malcolm Gladwell
2024/06/07
Most Commonly Used 3,000 Kanjis in Japanese
2024/06/07
Replace With Regex Using VSCode
2024/06/06
Do Not Use Readable Store in Svelte
2024/06/05
Increase Website Load Speed by Compressing Data with Gzip and Pako
2024/05/31
Find the Word the Mouse is Pointing to on a Webpage with JavaScript
2024/05/29
Create an Interactive Map with Svelte using SVG
2024/05/28
Book Review | Originals: How Non-Conformists Move the World by Adam Grant & Sheryl Sandberg
2024/05/27
How to Algorithmically Solve Sudoku Using Javascript
2024/05/26
How I Increased Traffic to my Website by 10x in a Month
2024/05/24
Life is Like Cycling
2024/05/19
Generate a Complete Sudoku Grid with Backtracking Algorithm in JavaScript
2024/05/16
Why Tailwind is Amazing and How It Makes Web Dev a Breeze
2024/05/15
Generate Sitemap Automatically with Git Hooks Using Python
2024/05/14
Book Review | Range: Why Generalists Triumph in a Specialized World by David Epstein
2024/05/13
What is Svelte and SvelteKit?
2024/05/12
Internationalization with SvelteKit (Multiple Language Support)
2024/05/11
Reduce Svelte Deploy Time With Caching
2024/05/10
Lazy Load Content With Svelte and Intersection Oberver
2024/05/10
Find the Optimal Stock Portfolio with a Genetic Algorithm
2024/05/09
Convert ShapeFile To SVG With Python
2024/05/07
Book Review | The Art Of War by Sun Tzu
2024/05/06
Specialists Are Dead. Long Live Generalists!
2024/05/03
Analyze Voter Behavior in Turkish Elections with Python
2024/05/01
Create Turkish Voter Profile Database With Web Scraping
2024/04/30
Make Infinite Scroll With Svelte and Tailwind
2024/04/29
How I Reached Japanese Proficiency In Under A Year
2024/04/25
Use-ready Website Template With Svelte and Tailwind
2024/01/29
Lazy Engineers Make Lousy Products
2024/01/28
On Greatness
2024/01/28
Converting PDF to PNG on a MacBook
2023/12/31
Recapping 2023: Compilation of 24 books read
2023/12/30
Create a Photo Collage with Python PIL
2024/01/09
Detect Device & Browser of Visitors to Your Website
2024/01/19
Anatomy of a ChatGPT Response