The point of Svelte stores

Why

In single-page applications, different pages are constructed using components. Often you need to share some data across them. Also, after the initial server render further interactions happen on the client-side, so, you need some way to store the initial state you got from the server.

What

Many frameworks have their respective recommended way of managing the state. Angular has Rxjs, React with Redux, and Svelte has Svelte-stores

How

Instead of how these state libraries work internally, let’s look at how these are used in an app, specifically Svelte.

Diagram

An image always makes more sense before we look at the code 

Code

Working Sample Code hosted online at REPL

App.svelte

Login.svelte

Dashboard.svelte

store.js

Now, go fix some bugs!

Dollar $ign is back in JS, don’t worry it’s not JQuery

It’s made its way back in Svelte. It is used to make statements reactive.

Reactivity is not new to software engineering, anybody with basics of Excel knows it.

For example this simple function below makes B3 react to changes in B1 or B2

Here is a Svelte implementation of the same thing, notice line 5 and the usage of $: that makes sumOfTwo react to changes in val1 or val2. Internally Svelte is using JavaScript’s label syntax

If you want to edit and try the REPL here

This also works across different components using Svelte stores, but how stores work is worth going through in another post. Now, go fix some bugs!