This chapter covers:
- Defining writable, readable, derived, and custom stores
- Using stores to share data between components
- Using stores in conjunction with JavaScript classes
- Persisting stores
This chapter focuses on using stores to share data between components, regardless of their relationship in the component hierarchy. Stores provide an alternative to using props or context. They hold application state outside any component. Each store holds a single JavaScript value, but the value can be an array or an object, which of course can hold many values.
Svelte supports several kinds of stores.
- Writable stores allow components to change their data.
- Readable stores do not allow changes.
- Derived stores compute their value from other stores.
- Custom stores can do any of these things and often provide a custom API for controlling their use.
Every store has a subscribe
method that returns a function you can call to unsubscribe.
The built-in support for stores is so useful that there is really no need for state management libraries. Such libraries are commonly used with other frameworks. For example, Angular has @ngrx/store, React has Redux, and Vue has Vuex.
To create a writable store, call the writable
function, which is defined in the svelte/store
package. Pass an initial value and optionally a function that initializes the store. The use of such a function is described later.
In addition to the subscribe
method, writable stores have the following methods: