6 Stores

 

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.

6.1  Writable stores

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:

6.2  Readable stores

6.3  Where to define stores

6.4  Using stores

6.5  Derived stores

6.6  Custom stores

6.7  Using stores with classes

6.8  Persisting stores

6.9  Building the Travel Packing app

6.10  Summary

sitemap