0
0
SvelteHow-ToBeginner · 3 min read

How to Subscribe to Store in Svelte: Simple Guide

In Svelte, you subscribe to a store by using the $ 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.

javascript
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.

svelte
<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>
Output
Count: 0 [ - ] [ + ] buttons update count reactively
⚠️

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.

svelte
/* 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 update or set to change store values.

Key Takeaways

Use the $ prefix to subscribe reactively to stores in Svelte components.
Manual subscriptions require calling the unsubscribe function to avoid memory leaks.
Without the $ prefix, you get the store object, not its current value.
Use writable stores with update or set methods to change values.
Reactive subscriptions update the UI automatically when the store changes.