State management with stores
Learning objectives
- You know the basics of state management with Svelte.
Previously, we briefly looked into passing data such as variable values and functions to child components as properties. As with any component-based application, relying on passing properties will eventually become cumbersome. To avoid this, some sort of a state management approach is needed. For example, with React, one could use libraries such as Redux or MobX. Svelte also comes with its own approach for state management.
State in Svelte is managed using stores. Stores are objects that can be imported to any part of the program, that can be subscribed to (to monitor changes), and that can be modified.
Let's define a simple store that holds a number into a file called countStore.js
. The file looks as follows.
import { writable } from 'svelte/store';
const count = writable(0);
export { count };
Now, in our components, we can import the file countStore.js
, and start using the store. As an example, we could modify our prior example for counting button clicks to import the count
variable from the store and use it directly.
<script>
import { count } from "./countStore.js";
const increment = () => {
$count++;
};
</script>
<button on:click={increment}>{$count}</button>
Again the dollar?
When using stores, the dollar sign is used as a shorthand to subscribe and to publish to stores. Do not use the dollar sign with non-store variables.
With the above implementation, we could create another component that relies on the count store. The following component would simply show the value of count.
<script>
import { count } from "./countStore.js";
</script>
<p>The count is {$count}</p>
The interesting part here is that the above component could be used anywhere in the component hierarchy (given that the relative path to the countStore.js
is correct). That is, there is no need to pass properties etc.
Your own stores
You can also implement your own stores. The documentation on store contract outlines the key parts for this.