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.
- Writable stores allow components to change their data.
- Readable stores do not allow components to change their data because the store itself can change its own data.
- 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.
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.