Reactivity In Svelte: Variables, Binding, and Key Function

Published: May 8, 2024

Reactivity In Svelte: Variables, Binding, and Key Function

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.

Reactivity in Svelte

Imagine you have below setting where user name needs to be reflected like below:

Welcome Galileo

You can achieved this eacilty in Svelte with binding.

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:

Welcome Kepler

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.

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:

Welcome Copernicus

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:

Welcome Newton

Where does reactivity break?

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:

Hello Einstein

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.

Svelte Reactivity Does Not Work On Derived Values

In complex apps, we are sure to have derived variables, so how can we make those variables reactive?

Make Derived Variables Reactive: 1. $ Sign

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:

Hello Stephen

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.

Make Derived Variables Reactive: 2. Key Function

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.

Hello Carl

Conclusion

In this post, we explored reactivity in svelte. Main topics covered are

  • Declare variable in script
  • 2-way bindings
  • Event bindings

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:

  • $ (Dollar) Sign
  • Key Function

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.

Svelte Is Better Than React, Angular and Vue Combined

Let me know in case of any questions.

Happy hacking!

Leave comment

Comments

Check out other blog posts

Create A Simple and Dynamic Tooltip With Svelte and JavaScript

2024/06/19

Create A Simple and Dynamic Tooltip With Svelte and JavaScript

JavaScriptSvelteSimpleDynamicTooltipFront-end
Create an Interactive Map of Tokyo with JavaScript

2024/06/17

Create an Interactive Map of Tokyo with JavaScript

SvelteSVGJavaScriptTailwindInteractive MapTokyoJapanTokyo Metropolitan Area23 Wards
How to Easily Fix Japanese Character Issue in Matplotlib

2024/06/14

How to Easily Fix Japanese Character Issue in Matplotlib

MatplotlibGraphChartPythonJapanese charactersIssueBug
Book Review | Talking to Strangers: What We Should Know about the People We Don't Know by Malcolm Gladwell

2024/06/13

Book Review | Talking to Strangers: What We Should Know about the People We Don't Know by Malcolm Gladwell

Book ReviewTalking to StrangersWhat We Should Know about the People We Don't KnowMalcolm Gladwell
Most Commonly Used 3,000 Kanjis in Japanese

2024/06/07

Most Commonly Used 3,000 Kanjis in Japanese

Most CommonKanji3000ListUsage FrequencyJapaneseJLPTLanguageStudyingWordsKanji ImportanceWord Prevalence
Replace With Regex Using VSCode

2024/06/07

Replace With Regex Using VSCode

VSCodeRegexFindReplaceConditional Replace
Do Not Use Readable Store in Svelte

2024/06/06

Do Not Use Readable Store in Svelte

SvelteReadableWritableState ManagementStoreSpeedMemoryFile Size
Increase Website Load Speed by Compressing Data with Gzip and Pako

2024/06/05

Increase Website Load Speed by Compressing Data with Gzip and Pako

GzipCompressionPakoWebsite Load SpeedSvelteKit
Find the Word the Mouse is Pointing to on a Webpage with JavaScript

2024/05/31

Find the Word the Mouse is Pointing to on a Webpage with JavaScript

JavascriptMousePointerHoverWeb Development
Create an Interactive Map with Svelte using SVG

2024/05/29

Create an Interactive Map with Svelte using SVG

SvelteSVGInteractive MapFront-end
Book Review | Originals: How Non-Conformists Move the World by Adam Grant & Sheryl Sandberg

2024/05/28

Book Review | Originals: How Non-Conformists Move the World by Adam Grant & Sheryl Sandberg

Book ReviewOriginalsAdam Grant & Sheryl SandbergHow Non-Conformists Move the World
How to Algorithmically Solve Sudoku Using Javascript

2024/05/27

How to Algorithmically Solve Sudoku Using Javascript

Solve SudokuAlgorithmJavaScriptProgramming
How I Increased Traffic to my Website by 10x in a Month

2024/05/26

How I Increased Traffic to my Website by 10x in a Month

Increase Website TrafficClicksImpressionsGoogle Search Console
Life is Like Cycling

2024/05/24

Life is Like Cycling

CyclingLifePhilosophySuccess
Generate a Complete Sudoku Grid with Backtracking Algorithm in JavaScript

2024/05/19

Generate a Complete Sudoku Grid with Backtracking Algorithm in JavaScript

SudokuComplete GridBacktracking AlgorithmJavaScript
Why Tailwind is Amazing and How It Makes Web Dev a Breeze

2024/05/16

Why Tailwind is Amazing and How It Makes Web Dev a Breeze

TailwindAmazingFront-endWeb Development
Generate Sitemap Automatically with Git Hooks Using Python

2024/05/15

Generate Sitemap Automatically with Git Hooks Using Python

Git HooksPythonSitemapSvelteKit
Book Review | Range: Why Generalists Triumph in a Specialized World by David Epstein

2024/05/14

Book Review | Range: Why Generalists Triumph in a Specialized World by David Epstein

Book ReviewRangeDavid EpsteinWhy Generalists Triumph in a Specialized World
What is Svelte and SvelteKit?

2024/05/13

What is Svelte and SvelteKit?

SvelteSvelteKitFront-endVite
Internationalization with SvelteKit (Multiple Language Support)

2024/05/12

Internationalization with SvelteKit (Multiple Language Support)

InternationalizationI18NSvelteKitLanguage Support
Reduce Svelte Deploy Time With Caching

2024/05/11

Reduce Svelte Deploy Time With Caching

SvelteEnhanced ImageCachingDeploy Time
Lazy Load Content With Svelte and Intersection Oberver

2024/05/10

Lazy Load Content With Svelte and Intersection Oberver

Lazy LoadingWebsite Speed OptimizationSvelteIntersection Observer
Find the Optimal Stock Portfolio with a Genetic Algorithm

2024/05/10

Find the Optimal Stock Portfolio with a Genetic Algorithm

Stock marketPortfolio OptimizationGenetic AlgorithmPython
Convert ShapeFile To SVG With Python

2024/05/09

Convert ShapeFile To SVG With Python

ShapeFileSVGPythonGeoJSON
Book Review | The Art Of War by Sun Tzu

2024/05/07

Book Review | The Art Of War by Sun Tzu

Book ReviewThe Art Of WarSun TzuThomas Cleary
Specialists Are Dead. Long Live Generalists!

2024/05/06

Specialists Are Dead. Long Live Generalists!

SpecialistGeneralistParadigm ShiftSoftware Engineering
Analyze Voter Behavior in Turkish Elections with Python

2024/05/03

Analyze Voter Behavior in Turkish Elections with Python

TurkeyAge Analysis2018 ElectionsVoter Behavior
Create Turkish Voter Profile Database With Web Scraping

2024/05/01

Create Turkish Voter Profile Database With Web Scraping

PythonSeleniumWeb ScrapingTurkish Elections
Make Infinite Scroll With Svelte and Tailwind

2024/04/30

Make Infinite Scroll With Svelte and Tailwind

SvelteTailwindInfinite ScrollFront-end
How I Reached Japanese Proficiency In Under A Year

2024/04/29

How I Reached Japanese Proficiency In Under A Year

JapaneseProficiencyJLPTBusiness
Use-ready Website Template With Svelte and Tailwind

2024/04/25

Use-ready Website Template With Svelte and Tailwind

Website TemplateFront-endSvelteTailwind
Lazy Engineers Make Lousy Products

2024/01/29

Lazy Engineers Make Lousy Products

Lazy engineerLousy productStarbucksSBI
On Greatness

2024/01/28

On Greatness

GreatnessMeaning of lifeSatisfactory lifePurpose
Converting PDF to PNG on a MacBook

2024/01/28

Converting PDF to PNG on a MacBook

PDFPNGMacBookAutomator
Recapping 2023: Compilation of 24 books read

2023/12/31

Recapping 2023: Compilation of 24 books read

BooksReading2023Reflections
Create a Photo Collage with Python PIL

2023/12/30

Create a Photo Collage with Python PIL

PythonPILImage ProcessingCollage
Detect Device & Browser of Visitors to Your Website

2024/01/09

Detect Device & Browser of Visitors to Your Website

JavascriptDevice DetectionBrowser DetectionWebsite Analytics
Anatomy of a ChatGPT Response

2024/01/19

Anatomy of a ChatGPT Response

ChatGPTLarge Language ModelMachine LearningGenerative AI