Beliebte Suchanfragen

Cloud Native

DevOps

IT-Security

Agile Methoden

Java

|
//

State management in Svelte

25.2.2020 | 3 minutes of reading time

In 2020, web development is not only based on component-driven approaches but also on the use of state management solutions. These solutions are usually oriented towards the Flux architecture and its most prominent representative, Redux . That’s why it is not surprising that Svelte also brings a suitable solution here, which I present in the following article. The code shown here is taken from the official tutorial .

Interested in Svelte basics first? Have a look at my introduction to Svelte .

First steps

Svelte comes with its own store implementation, as already mentioned. If we want to implement a store that manages the state of a counter, for example, we only need two lines of code:

1import { writable } from 'svelte/store';
2 
3export const count = writable(0);

The store is implemented as writeable (we will get to the read-only counterpart later) and we create a store with the initial state (here 0). The count variable exported here offers three methods:

  • subscribe(callback): executed when the store is updated. The callback function gets the initial value in the store as parameter
  • update(callback): executes the callback. The callback function gets the initial value in the store as parameter
  • set(value): sets the value in the store to the transferred value value

In a Svelte component a counter could look like this:

1<script>
2 import { count } from "./store";
3 
4 let count_value;
5 function increment() {
6   count.update(n => n + 1);
7 }
8 function decrement() {
9   count.update(n => n - 1);
10 }
11 function reset() {
12   count.set(0);
13 }
14count.subscribe(value => {
15   count_value = value;
16 });
17</script>
18 
19<h1>The count is {count_value}</h1>
20<button on:click="{increment}">
21 +
22</button>
23<button on:click="{decrement}">
24 -
25</button>
26<button on:click="{reset}">
27 Reset
28</button>

You can save the usage of the subscribe function by using the short form $count:

1<script>
2 import { count } from "./store";
3 
4 function increment() {
5   count.update(n => n + 1);
6 }
7 function decrement() {
8   count.update(n => n - 1);
9 }
10 function reset() {
11   count.set(0);
12 }
13</script>
14 
15<h1>The count is {$count}</h1>
16<button on:click="{increment}">
17 +
18</button>
19<button on:click="{decrement}">
20 -
21</button>
22<button on:click="{reset}">
23 Reset
24</button>

The $ character is a reserved character in Svelte, which must always refer to a store. So it is not allowed to use it for your own variables.

Custom stores

Now you do not always want to interact directly with the store within a component. In Redux there are Reducers and Actions, with which you can trigger changes to the state. In Svelte we can create a custom store, for which we can define our own operations. The advantage here is that you need less boilerplate code to manipulate the state.

1import { writable } from "svelte/store";
2 
3function createCount() {
4 const { subscribe, set, update } = writable(0);
5 
6 return {
7   subscribe,
8   increment: () => update(n => n + 1),
9   decrement: () => update(n => n - 1),
10   reset: () => set(0)
11 };
12}
13 
14export const count = createCount();

In the component we save a lot of code and make everything a bit clearer:

1<script>
2 import { count } from "./store";
3</script>
4 
5<h1>The count is {$count}</h1>
6<button on:click="{count.increment}">
7 +
8</button>
9<button on:click="{count.decrement}">
10 -
11</button>
12<button on:click="{count.reset}">
13 Reset
14</button>

Readable and derived store

In addition to the writeable store, Svelte offers two more appealing options: the readable store and the derived store.

The readable store is, as the name suggests, a read-only store. It can be used if the data managed in the store should not be manipulated by the user.

The derived store allows you to manage data dependent on other stores. This way, complexity in individual stores can be avoided by outsourcing them to derived stores.

Conclusion

Svelte is not reinventing the wheel when it comes to state management: We are already familiar with the idea of implementing state management via stores from React, Angular and Vue. Nevertheless, the solution established by Svelte is interesting: read-only and derived stores solve known problems in front-end applications. The possibility to create custom stores saves a lot of boilerplate code (which can be replaced by libraries ) and allows you to implement the stores with domain-specific logic.

Picture by Mike Petrucci

|

share post

Likes

2

//

More articles in this subject area

Discover exciting further topics and let the codecentric world inspire you.

//

Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.