Managing cross-component state
In Chapter 3, Building Reactive Svelte Components, we looked at how to use props, bindings, and events to pass variables between components, including from parents to children and vice versa. However, sometimes it's useful to maintain a state that is shared across multiple components, even those not having direct relationships.
Svelte stores
Svelte stores can be used precisely for this purpose. They provide readable and writable stores that can be accessed by any component in the application, while being fully reactive. That means that if a component depends on a store and the value of such a store changes, Svelte automatically re-executes all reactive statements and templates that depend on it.
In the previous chapter, we created a src/stores.js
file with pre-made content. Let's take another look at it here:
src/stores.js
import {writable, derived} from 'svelte/store' export const profile = writable(null) export const...