Skip to content

docs: update store documentation #14083

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
280 changes: 55 additions & 225 deletions documentation/docs/06-runtime/01-stores.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,15 @@
title: Stores
---

<!-- - how to use
- how to write
- TODO should the details for the store methods belong to the reference section? -->
> [!NOTE] Prior to the introduction of runes, stores were the primary state management mechanism for anything that couldn't be expressed as component state or props. With runes — which can be used in [`.svelte.js/ts`](svelte-js-files) files as well as in components — stores are rarely necessary, though you will still sometimes encounter them when using Svelte.

A _store_ is an object that allows reactive access to a value via a simple _store contract_. The [`svelte/store` module](../svelte-store) contains minimal store implementations which fulfil this contract.
A _store_ is an object that allows reactive access to a value via a simple [_store contract_](#Store-contract). The [`svelte/store`](../svelte-store) module contains minimal store implementations that fulfil this contract.

Any time you have a reference to a store, you can access its value inside a component by prefixing it with the `$` character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialisation and unsubscribe when appropriate.
Inside a component, you can reference the store's value by prefixing it with the `$` character. (You cannot use this prefix to declare or import local variables, as it is reserved for store values.)

Assignments to `$`-prefixed variables require that the variable be a writable store, and will result in a call to the store's `.set` method.
The component will subscribe to the store when it mounts, and unsubscribe when it unmounts. The store must be declared (or imported) at the top level of the component — not inside an `if` block or a function, for example.

Note that the store must be declared at the top level of the component — not inside an `if` block or a function, for example.

Local variables (that do not represent store values) must _not_ have a `$` prefix.
If the store is [writable](#Store-contract-Writable-stores), assigning to (or mutating) the store value will result in a call to the store's `set` method.

```svelte
<script>
Expand All @@ -26,260 +22,94 @@ Local variables (that do not represent store values) must _not_ have a `$` prefi
count.set(1);
console.log($count); // logs 1

$count = 2;
$count++;
console.log($count); // logs 2
</script>
```

## When to use stores

Prior to Svelte 5, stores were the go-to solution for creating cross-component reactive states or extracting logic. With runes, these use cases have greatly diminished.

- when extracting logic, it's better to take advantage of runes' universal reactivity: You can use runes outside the top level of components and even place them into JavaScript or TypeScript files (using a `.svelte.js` or `.svelte.ts` file ending)
- when creating shared state, you can create a `$state` object containing the values you need and then manipulate said state

Stores are still a good solution when you have complex asynchronous data streams or it's important to have more manual control over updating values or listening to changes. If you're familiar with RxJs and want to reuse that knowledge, the `$` also comes in handy for you.

## svelte/store

The `svelte/store` module contains a minimal store implementation which fulfil the store contract. It provides methods for creating stores that you can update from the outside, stores you can only update from the inside, and for combining and deriving stores.

### `writable`

Function that creates a store which has values that can be set from 'outside' components. It gets created as an object with additional `set` and `update` methods.

`set` is a method that takes one argument which is the value to be set. The store value gets set to the value of the argument if the store value is not already equal to it.

`update` is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.

```js
/// file: store.js
import { writable } from 'svelte/store';

const count = writable(0);

count.subscribe((value) => {
console.log(value);
}); // logs '0'

count.set(1); // logs '1'

count.update((n) => n + 1); // logs '2'
```

If a function is passed as the second argument, it will be called when the number of subscribers goes from zero to one (but not from one to two, etc). That function will be passed a `set` function which changes the value of the store, and an `update` function which works like the `update` method on the store, taking a callback to calculate the store's new value from its old value. It must return a `stop` function that is called when the subscriber count goes from one to zero.

```js
/// file: store.js
import { writable } from 'svelte/store';

const count = writable(0, () => {
console.log('got a subscriber');
return () => console.log('no more subscribers');
});

count.set(1); // does nothing

const unsubscribe = count.subscribe((value) => {
console.log(value);
}); // logs 'got a subscriber', then '1'

unsubscribe(); // logs 'no more subscribers'
```

Note that the value of a `writable` is lost when it is destroyed, for example when the page is refreshed. However, you can write your own logic to sync the value to for example the `localStorage`.

### `readable`

Creates a store whose value cannot be set from 'outside', the first argument is the store's initial value, and the second argument to `readable` is the same as the second argument to `writable`.

```ts
import { readable } from 'svelte/store';

const time = readable(new Date(), (set) => {
set(new Date());

const interval = setInterval(() => {
set(new Date());
}, 1000);

return () => clearInterval(interval);
});

const ticktock = readable('tick', (set, update) => {
const interval = setInterval(() => {
update((sound) => (sound === 'tick' ? 'tock' : 'tick'));
}, 1000);
## Store contract

return () => clearInterval(interval);
});
```
To be considered a store, an object must implement the [`Readable`](svelte-store#Readable) interface. It can additionally implement the [`Writable`](svelte-store#Writable) interface. Beyond that, a store can include whatever methods and properties it needs.

### `derived`
### Readable stores

Derives a store from one or more other stores. The callback runs initially when the first subscriber subscribes and then whenever the store dependencies change.
A readable store is an object with a `subscribe(fn)` method, where `fn` is a subscriber function. This subscriber function must be immediately and synchronously called with the store's current value upon calling `subscribe`, and the function must be added to the store's list of subscribers. All of a store's subscribers must later be synchronously called whenever the store's value changes.

In the simplest version, `derived` takes a single store, and the callback returns a derived value.
The `subscribe` method must return a function which, when called, removes the subscriber.

```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';

declare global {
const a: Writable<number>;
}

export {};

// @filename: index.ts
import type { Readable } from 'svelte/store';
const readable = {} as Readable<any>;
// ---cut---
import { derived } from 'svelte/store';
const unsubscribe = readable.subscribe((value) => {
console.log(value);
});

const doubled = derived(a, ($a) => $a * 2);
// later
unsubscribe();
```

The callback can set a value asynchronously by accepting a second argument, `set`, and an optional third argument, `update`, calling either or both of them when appropriate.

In this case, you can also pass a third argument to `derived` — the initial value of the derived store before `set` or `update` is first called. If no initial value is specified, the store's initial value will be `undefined`.
> [!NOTE] Advanced: if a second argument is provided to `subscribe`, it must be called before the subscriber itself is called. This provides a mechanism for glitch-free updates.

```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';
### Writable stores

declare global {
const a: Writable<number>;
}
A writable store is a readable store with `set` and `update` methods.

export {};

// @filename: index.ts
// @errors: 18046 2769 7006
// ---cut---
import { derived } from 'svelte/store';

const delayed = derived(
a,
($a, set) => {
setTimeout(() => set($a), 1000);
},
2000
);

const delayedIncrement = derived(a, ($a, set, update) => {
set($a);
setTimeout(() => update((x) => x + 1), 1000);
// every time $a produces a value, this produces two
// values, $a immediately and then $a + 1 a second later
});
```

If you return a function from the callback, it will be called when a) the callback runs again, or b) the last subscriber unsubscribes.
The `set` method takes a new value...

```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';

declare global {
const frequency: Writable<number>;
}

export {};

// @filename: index.ts
import type { Writable } from 'svelte/store';
const writable = {} as Writable<string>;
// ---cut---
import { derived } from 'svelte/store';

const tick = derived(
frequency,
($frequency, set) => {
const interval = setInterval(() => {
set(Date.now());
}, 1000 / $frequency);

return () => {
clearInterval(interval);
};
},
2000
);
writable.set('new value');
```

In both cases, an array of arguments can be passed as the first argument instead of a single store.
...while the `update` method transforms the existing value:

```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';

declare global {
const a: Writable<number>;
const b: Writable<number>;
}

export {};

// @filename: index.ts

import type { Writable } from 'svelte/store';
const writable = {} as Writable<string>;
const transform = (value: string) => value;
// ---cut---
import { derived } from 'svelte/store';

const summed = derived([a, b], ([$a, $b]) => $a + $b);

const delayed = derived([a, b], ([$a, $b], set) => {
setTimeout(() => set($a + $b), 1000);
});
writable.update((value) => transform(value));
```

### `readonly`

This simple helper function makes a store readonly. You can still subscribe to the changes from the original one using this new readable store.

```js
import { readonly, writable } from 'svelte/store';
Generally, these methods will have a synchronous effect but this is not required by the contract — for example in the case of [`spring`](svelte-motion#spring) and [`tweened`](svelte-motion#tweened) it will set a target value, and subscribers will be notified in `requestAnimationFrame` callbacks.

const writableStore = writable(1);
const readableStore = readonly(writableStore);
### RxJS interoperability

readableStore.subscribe(console.log);
For interoperability with [RxJS Observables](https://rxjs.dev/guide/observable), the `subscribe` method is also allowed to return an `{ unsubscribe }` object rather than the function itself.

writableStore.set(2); // console: 2
// @errors: 2339
readableStore.set(2); // ERROR
```

### `get`
Note that unless `observable.subscribe(fn)` synchronously calls `fn` (which is not required by the Observable spec), Svelte will see the value of `$observable` as `undefined` until it does.

Generally, you should read the value of a store by subscribing to it and using the value as it changes over time. Occasionally, you may need to retrieve the value of a store to which you're not subscribed. `get` allows you to do so.
## Creating custom stores

> [!NOTE] This works by creating a subscription, reading the value, then unsubscribing. It's therefore not recommended in hot code paths.
In general, you won't be implementing the subscription logic yourself. Instead, you will use the reference implementations in [`svelte/store`](svelte/store) even if you expose a custom interface ([demo](/playground/hello-world#H4sIAAAAAAAAE42Q0U7DMAxFf8WKkNaKsm6vpa2EeOEfCA9t6mkRrVMlLgNV-XeUdssQQsBTHPvcm1zPgpoBRSGesO8NnIztO0iw04xdKjJx0D06UTzPgj_GwIWGyC6qh3HcujfsOfTaxuFPfWWIkdiJQpROWT1yLUmyHkZjGWY4Wc1N2yN4OFgzwGZV5o6Nxc29pEAfJlKsDYGy2DA-mokYbZLCHKaSlSEXzNzUhjdazMAhZzCNXcPBuorvJLv0bCrZIk-WLiaSr_JLR5OyOCBxAUkKVX12TBJabgS3sE8j3eEf9N1X2qLDSDrkZJeuIx8-yH795RpNrYmh-r6Be0llft0rlcd9vcAFzDdnlS_z476WVLYTsyEwpHqtXqv5PN_GlL6OZZmv9G-6mNfXsfyPbknu6-WIvMgE4zuLgu2E_sV_AkFYhfmdAgAA)):

```ts
// @filename: ambient.d.ts
import { type Writable } from 'svelte/store';

declare global {
const store: Writable<string>;
}
```svelte
<!--- file: App.svelte --->
<script>
import { writable } from 'svelte/store';

export {};
function createCounter() {
const { subscribe, set, update } = writable(0);

// @filename: index.ts
// ---cut---
import { get } from 'svelte/store';

const value = get(store);
```
return {
subscribe,
increment: () => update((n) => n + 1),
decrement: () => update((n) => n - 1),
reset: () => set(0)
};
}

## Store contract
const counter = createCounter();
</script>

```ts
// @noErrors
store = { subscribe: (subscription: (value: any) => void) => (() => void), set?: (value: any) => void }
<h1>count: {$counter}</h1>
<button onclick={counter.increment}>increment</button>
<button onclick={counter.decrement}>decrement</button>
<button onclick={counter.reset}>reset</button>
```

You can create your own stores without relying on [`svelte/store`](../svelte-store), by implementing the _store contract_:

1. A store must contain a `.subscribe` method, which must accept as its argument a subscription function. This subscription function must be immediately and synchronously called with the store's current value upon calling `.subscribe`. All of a store's active subscription functions must later be synchronously called whenever the store's value changes.
2. The `.subscribe` method must return an unsubscribe function. Calling an unsubscribe function must stop its subscription, and its corresponding subscription function must not be called again by the store.
3. A store may _optionally_ contain a `.set` method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. Such a store is called a _writable store_.

For interoperability with RxJS Observables, the `.subscribe` method is also allowed to return an object with an `.unsubscribe` method, rather than return the unsubscription function directly. Note however that unless `.subscribe` synchronously calls the subscription (which is not required by the Observable spec), Svelte will see the value of the store as `undefined` until it does.