Skip to main content

Not all application state belongs inside your application's component hierarchy. Sometimes, you'll have values that need to be accessed by multiple unrelated components, or by a regular JavaScript module.

In Svelte, we do this with stores. A store is simply an object with a subscribe method that allows interested parties to be notified whenever the store value changes. In App.svelte, count is a store, and we're setting count_value in the count.subscribe callback.

Open stores.js to see the definition of count. It's a writable store, which means it has set and update methods in addition to subscribe.

Now, in Incrementer.svelte, wire up the + button:

Incrementer.svelte
function increment() {
	count.update((n) => n + 1);
}

Clicking the + button should now update the count. Do the inverse for Decrementer.svelte.

Finally, in Resetter.svelte, implement reset:

Resetter.svelte
function reset() {
	count.set(0);
}

Next: Auto-subscriptions

<script>
import { count } from './stores.js';
import Incrementer from './Incrementer.svelte';
import Decrementer from './Decrementer.svelte';
import Resetter from './Resetter.svelte';

let count_value;

count.subscribe((value) => {
count_value = value;
});
</script>

<h1>The count is {count_value}</h1>

<Incrementer />
<Decrementer />
<Resetter />


> tutorial@0.0.1 dev
> ./node_modules/vite/bin/vite.js dev


Forced re-optimization of dependencies

VITE v4.3.9 ready in 2814 ms

Local: http://localhost:5173/
Network: use --host to expose
press h to show help
7:41:19 PM [vite] Failed to load source map for /@vite/client.
7:41:19 PM [vite] Failed to load source map for /node_modules/vite/dist/client/env.mjs.