All articles
  • Svelte
  • State Management
  • Stores

Why is Svelte becoming a developers favourite? (pt 2)

Part 2 of our Svelte journey looks at how Svelte handles state outside of the component hierarchy — the context API and stores, and the three store types: writable, readable and derived.

3 min read
Why is Svelte becoming a developers favourite? Part 2

Welcome back to Part 2 of our blog series on our Svelte journey, where we look into all of Svelte’s peculiarities and features as our team discovered them after first six months of using Svelte.

The previous time, we discussed how Svelte manages state within the component hierarchy. We’ll investigate Svelte’s handling of state outside of the component hierarchy this time. Developers can accomplish this using Svelte in one of two ways: by using context API or storage.

The two alternatives differ primarily in that stores are available throughout the entire application, including all modules and/or components, but the context API is only available to the individual components. Stores are also reactive, whereas context is not. Store in Svelte is simply an object that has a subscribe method that allows interested parties to be notified whenever the store value changes. Svelte has 3 different store types:

  • writable
  • readable
  • derived

Writable stores allow us to read and write data, whereas readable and derived allow us to only read the stored data. For example we would create a store like by calling the appropriate function from the Svelte “store” module:

javascript
// ./store.js
import { writable } from 'svelte/store';

export const count = writable(0);
svelte
import { count } from './store.js';

let countValue;
const unsubscribe = count.subscribe((value) => {
    countValue = value;
});

The count is {countValue}

Once we have the unsubscribe function we can use it inside of the onDestroy lifecycle hook which is just a function that runs when our component is destroyed.

svelte
import { count } from './store.js';

let countValue;
const unsubscribe = count.subscribe((value) => {
    countValue = value;
});

onDestroy(() => {
    unsubscribe();
});

The count is {countValue}

Svelte also provides an auto-subscription that references a store value by prefixing the store name with the $ character:

svelte
import { count } from './stores.js';

The count is {$count}
javascript
import { readable } from 'svelte/store';

export const time = readable(new Date(), function start(set) {
    const interval = setInterval(() => {
        set(new Date());
    }, 1000);

    return function stop() {
        clearInterval(interval);
    };
});

The first argument that our store requires is a default value and a start function that runs when the store gets the first subscriber and returns a stop function that runs when the last subscriber unsubscribes. Also we have derived stores who base their values on one or more other stores. Building on our previous example, we can create a store that derives the time the page has been open:

javascript
export const elapsed = derived(time, ($time) =>
    Math.round(($time - start) / 1000)
);
javascript
function createCount() {
    const { subscribe, set, update } = writable(0);

    return {
        subscribe,
        increment: () => update((n) => n + 1),
        decrement: () => update((n) => n - 1),
        reset: () => set(0)
    };
}

What we get in the end is the object that implements the subscribe method and 3 domain-specific methods tightly coupled to our store, which should be the preferred way to expose the store values and their coupled functionality.

That being said, Svelte stores in our experience, were an amazing tool to work with, allowing us to write concise and expressive code that exists to help us achieve desired functionality and not to weigh on the project with boilerplate that takes up space and means nothing. To complete the story of Svelte’s state management capabilities, we still need to cover the context API, so hang tight until the next one.

Tags:SvelteState ManagementStores

Work with us

Building something? Let’s talk.

Tell us what you’re working on — we’ll get back to you shortly.

Step 1 of 2