DEV Community

loading...
Cover image for Global state management in Svelte
IT Minds

Global state management in Svelte

simmetopia profile image Simon Bundgaard-Egeberg ・3 min read

Store all the things!

First of all, I would like to advocate what I think is a great strength of Svelte. I will make this short since I assume that everybody who writes a blog about Svelte, explains what it is. If interested look up svelte's homepage
on https://svelte.dev.

I use svelte for a tool to solve simple tasks. Do you need a site to ping microservices and show status for them? Do you need to show
a simple UI consuming an API? Svelte is perfect for these small components. What makes it really great, for me, is that I have all the tools in the Svelte toolbox, but the apps I create are still super lean, and basically cost-free to deploy, since all the things from Svelte I don't opt in to using, do not join my production bundle.

Enough talk, let me try to put my mouth where my money is.

Creating a svelte store is a bit like creating a database for your application.
You can have different types of persistence, you can have readable values, writeable values, and computed/derived values.

These concepts are mirrored in Svelte.

Writeable stores

import { writable } from 'svelte/store';

export const amountOfCoolPoints = writable(0);

Readable stores

import { readable } from 'svelte/store';

export const timeBasedLevel = readable(1, update=>{
   const interval = setInterval(()=>{
      const nVal = Math.floor(Math.random()*10)
      update(nVal)
   }, 1000);

   return ()=>clearInterval(interval);
});

Derived stores

import { derived } from 'svelte/store';

export const timeBasedCoolPoints = derived([timeBasedLevel, amountOfCoolPoints], values=>{
   const [TBLevel, cPoints] = values;
   return TBLevel * cPoints;
})

The test project

These things are relatively simple, but yet incredibly powerful. And one of the most interesting things
is the amount of effort and knowledge you need to commit, in order for you to get up and running with store management.

Creating a globally writeable piece of state is just 1 single line!

The sample project i equally small:

    <script>
        import { amountOfCoolPoints,timeBasedLevel, timeBasedCoolPoints} from './store'


        // Subscription method
        let level;
        timeBasedLevel.subscribe(v=>{level=v})

        // Demo up updating store values with set
        setTimeout(()=>{
            amountOfCoolPoints.set(7)
        }, 2000);
    </script>

    <p>
       time based Level:  {level}
    </p>
    <p>
       cool points:  {$amountOfCoolPoints}
    </p>
    <p>
       time based cool points:  {$timeBasedCoolPoints}
    </p>

Note here that I have used to different ways of getting values displayed in our page, the first one, which is
the 'manual' way, I create a variable, subscribe to the store, and update my local value on updates to the stored value.

This is fine, but also boilerplate, which is not the Svelte way. Therefore the $ syntax is provided.
If used in the template, this will do these things for you, as demonstrated by the cool points and the time based
cool points.

Basically this webpage will start with 0 coolPoints, which then means that we have 0 timeBasedcoolpoints and the timeBasedCoolPoints in derived
by multiplicating timeBasedLevel and amountOfCoolPoints. After 2 seconds though, our coolPoints are updated to 7, and now the numbers
start changing by an interval of 2, as set in the readable store.

Pretty neat.

These stores are global, but usage without proper management can turn a good framework into bad code.
Svelte provides all the tools, but it allows its users to create their own solutions, which is a thing I like.
This does sometimes demand more of the individual developer, especially in large-scale projects, but it's a tradeoff, I would be glad to pay.
And my motto is

There is never a reason to not do it properly

Discussion

pic
Editor guide