chapter six

6 Stores

 

This chapter covers 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 object which of course can hold many values. Instead the data is held in a JavaScript object that can be used from any component that has access to the store.

Svelte supports several kinds of stores.

  • Writable stores allow components to change their data.
  • Readable stores do not.
  • 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 builtin 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.

6.1  Kinds of stores

Svelte provides three kinds of stores.

  • Writable stores are the only kind that can be modified by components.
  • Readable stores handle computing their own data. Components cannot modify them.
  • Derived stores derive data from the current values of other stores.

Every store has a subscribe method that returns a function to call in order to unsubscribe.

6.2  Writable stores

6.3  Readable stores

6.4  Where to define stores

6.5  Using stores

6.6  Derived stores

6.7  Custom stores

6.8  get function

6.9  Using stores with classes

6.10  Persisting stores

6.11  Building the Travel Packing app

6.12  Summary