Skip to main content
Basic Svelte
Introduction
Reactivity
Props
Logic
Events
Bindings
Classes and styles
Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
Stores
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

Prior to the introduction of runes in Svelte 5, stores were the idiomatic way to handle reactive state outside components. That’s no longer the case, but you’ll still encounter stores when using Svelte (including in SvelteKit, for now), so it’s worth knowing how to use them.

We won’t cover how to create your own custom stores — for that, consult the documentation.

Let’s revisit the example from the universal reactivity exercise, but this time implement the shared state using a store.

In shared.js we’re currently exporting count, which is a number. Turn it into a writable store:

shared
import { writable } from 'svelte/store';

export const count = writable(0);

To reference the value of the store, we prefix it with a $ symbol. In Counter.svelte, update the text inside the <button> so that it no longer says [object Object]:

Counter
<button onclick={() => {}}>
	clicks: {$count}
</button>

Finally, add the event handler. Because this is a writable store, we can update the value programmatically using its set or update method...

count.update((n) => n + 1);

...but since we’re in a component we can continue using the $ prefix:

Counter
<button onclick={() => $count += 1}>
	clicks: {$count}
</button>

Edit this page on GitHub

1
2
3
4
5
6
7
8
<script>
	import Counter from './Counter.svelte';
</script>
 
<Counter />
<Counter />
<Counter />