0 day streak
javascript / intermediate
Snippet

Global State Management with Writable Stores

Writable stores provide a way to share state across multiple components without prop drilling. They implement the observable pattern, allowing components to subscribe to changes and update the UI reactively.

snippet.js
javascript
1
2
3
4
5
6
7
8
import { writable } from 'svelte/store';
export const count = writable(0);
// In a component:
// count.update(n => n + 1);
// count.set(0);
// $count // Auto-subscription
svelte
Breakdown
1
import { writable } from 'svelte/store';
Imports the writable function from the Svelte store module.
2
export const count = writable(0);
Creates a new store with an initial value of 0 and exports it for global use.
3
$count
The '$' prefix is a Svelte shortcut that handles subscribing and unsubscribing automatically.