How to Subscribe to Store in Svelte: Simple Guide
$ prefix before the store variable inside your component, which automatically subscribes and updates the value reactively. Alternatively, you can use the store.subscribe() method for manual subscription and cleanup.Syntax
To subscribe to a Svelte store reactively in a component, use the $ prefix before the store variable name. This syntax automatically subscribes to the store and updates the value when it changes.
For manual subscription, use store.subscribe(callback), which returns an unsubscribe function to stop listening.
import { writable } from 'svelte/store'; const count = writable(0); // Reactive subscription in component // Use $count to get current value and auto-subscribe // Manual subscription const unsubscribe = count.subscribe(value => { console.log('Count is', value); }); // Later, to stop listening unsubscribe();
Example
This example shows a simple counter using a writable store. The component uses $count to display the current count reactively and buttons to update it.
<script> import { writable } from 'svelte/store'; const count = writable(0); function increment() { count.update(n => n + 1); } function decrement() { count.update(n => n - 1); } </script> <h1>Count: {$count}</h1> <button on:click={decrement}>-</button> <button on:click={increment}>+</button>
Common Pitfalls
1. Forgetting the $ prefix: Without $, you get the store object, not its value, so the UI won't update.
2. Not unsubscribing manual subscriptions: When using store.subscribe() manually, always call the unsubscribe function to avoid memory leaks.
3. Using stores outside components without subscription: Accessing store values outside reactive contexts requires manual subscription or get() from svelte/store.
/* Wrong: No $ prefix, UI won't update */ <h1>Count: {count}</h1> /* Right: Use $ prefix for reactive value */ <h1>Count: {$count}</h1>
Quick Reference
$store: Reactive subscription in components.store.subscribe(callback): Manual subscription with unsubscribe.- Always unsubscribe manual subscriptions to prevent leaks.
- Use
updateorsetto change store values.