Svelte 47 ๐งก Reading Stores with Auto-Subscription ($store)
In the Svelte legacy ecosystem, a “store” is an object that holds a value and notifies subscribers when that value changes. Manually subscribing to these stores involves calling .subscribe() in onMount and calling the resulting cleanup function in onDestroy. To eliminate this repetitive and error-prone boilerplate, Svelte provides a compiler-level feature called “auto-subscription.” By prefixing a store variable with a $ sign, Svelte handles the subscription, UI updates, and cleanup automatically.
This chapter covers the mechanics of the $ auto-subscription syntax, how it enables both reading from and writing to stores, and when to use this legacy feature compared to modern Svelte 5 Runes. While Runes are the future of Svelte reactivity, understanding $store is essential for maintaining existing codebases and integrating with popular legacy libraries.
Key point: The $ prefix is a special Svelte compiler directive that signals an automatic subscription to a store, keeping a local reactive variable synced with the store’s value and ensuring that the subscription is disposed of correctly when the component is unmounted.
Why auto-subscription exists
The boilerplate tax.
Manually managing store subscriptions is verbose. Developers had to write custom logic to store the unsubscribe function and ensure it was called during component destruction. Auto-subscription turns three lines of management code into a single character prefix.
Automatic memory management.
Forgetting to unsubscribe from a store in a component results in memory leaks, as the store maintains a reference to the component’s callback function indefinitely. Svelteโs compiler ensures that the $ variable is scoped to the component lifecycle.
Reactive UI synchronization.
The $store syntax isn’t just a getter; it is a reactive hook. Whenever the store’s value changes, the Svelte compiler triggers an update for any template part that references that $store variable, keeping the view in sync with the data.
Declarative intent.
The $ prefix is a visual indicator that the variable is not just a standard local variable, but a reactive reference to an external store. This makes the data flow in components easier to audit at a glance.
Simplicity in writing.
For writable stores, auto-subscription provides a shortcut for updating values. Instead of calling .update() or .set(), the $ syntax allows you to use standard assignment operators, making the store feel like a local reactive variable.
a. Reading store values automatically
To use auto-subscription, simply prefix the variable name of your store with $. When the component renders, Svelte subscribes to the store and assigns its value to that local variable. If the store emits a new value, the component automatically re-evaluates the code block or template referencing that $store variable.
<script>
import { count } from './stores.js';
</script>
<!-- Svelte subscribes automatically here -->
<p>Current count: {$count}</p>
Behind the scenes, the Svelte compiler transforms this into a standard subscription pattern. You do not need to worry about calling the unsubscribe function; the compiler generates the necessary code to clean up when the component instance is destroyed.
b. Writing to writable stores
If a store is writable (meaning it has set and update methods), you can use the $store syntax to assign a new value directly. The compiler detects this assignment and calls the storeโs .set() method internally, which then triggers the broadcast of the new value to all subscribers.
<script>
import { count } from './stores.js';
function increment() {
$count += 1; // Compiler turns this into count.set($count + 1)
}
</script>
<button on:click={increment}>Increment</button>
This makes writable stores feel like standard let variables. It is a powerful way to bridge the gap between complex state management and simple, declarative UI updates, provided the store is defined in a scope accessible to the component.
c. When to use $ vs fromStore
The $store syntax is a legacy feature, while fromStore is the modern Rune-based approach. Use $store when you are maintaining older Svelte 4 code or working with libraries that strictly export stores. Use fromStore (the Rune) when writing new components in Svelte 5, as fromStore converts a store into a reactive Rune that behaves more predictably with $derived and $effect.
<script>
import { fromStore } from 'svelte/store';
import { count } from './stores.js';
// Modern way (Rune)
const countRune = fromStore(count);
$: double = countRune * 2;
// Legacy way (Compiler directive)
// $: double = $count * 2;
</script>
The $ syntax is global and component-scoped, whereas fromStore provides a value that can be passed as an argument to functions, stored in variables, or used inside other Runes, offering much greater architectural flexibility.
Complete Example Session
// ============================================
// PART 1: READ-ONLY AUTO-SUBSCRIPTION
// ============================================
<script>
import { name } from './stores.js';
</script>
<p>Hello, {$name}!</p>
// ============================================
// PART 2: MUTATING WRITABLE STORES
// ============================================
<script>
import { count } from './stores.js';
</script>
<button on:click={() => $count++}>Add</button>
// ============================================
// PART 3: MULTIPLE STORES
// ============================================
<p>{$a} + {$b} = {$a + $b}</p>
// ============================================
// PART 4: CONDITIONAL RENDERING
// ============================================
{#if $loggedIn}
<Dashboard />
{/if}
This session shows reading static values, triggering store mutations, performing math on multiple stores, and using stores in control flow.
Quick Reference
Syntax Cheat Sheet
| Operation | Syntax |
|---|---|
| Read Store | {$store} |
| Write Store | $store = newVal |
| Subscribe | Implicit (Compiler) |
| Unsubscribe | Implicit (Compiler) |
Rules
| Rule | Requirement |
|---|---|
| Availability | Store must be in scope |
| Scope | Component template and script |
| Compatibility | Only works with objects having .subscribe |
Best Practices
โ Do This:
// Read stores in the template
<p>{$count}</p> // โ
// Use auto-subscription for simple writable state
$count += 1; // โ
// Always import the store at the top level
import { count } from './stores.js'; // โ
โ Don’t Do This:
// Manually subscribe in script if not needed
count.subscribe(c => ...); // โ
// Use the $ prefix on non-store variables
$myLocalVariable = 5; // โ
// Use $syntax in standard JS files (non-.svelte)
// (It only works in .svelte files) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Reference Error | Store not imported | Check import path |
| UI not updating | Variable doesn’t have .subscribe | Verify store interface |
| Svelte error | Using $ on non-store | Remove $ prefix |
Real-World Examples
1. Page Title
<h1>{$title}</h1>
2. User Settings
<input bind:value={$username} />
3. Theme Toggle
<div class:dark={$theme === 'dark'} />
4. Loading Indicator
{#if $loading} <Spinner /> {/if}
5. Search Filter
<input bind:value={$searchQuery} />
6. Notification List
{#each $notifications as n} <li>{n}</li> {/each}
7. Cart Total
<p>Total: {$cartTotal}</p>
8. Toggle Switch
<button on:click={() => $on = !$on}>Toggle</button>
9. Error Alerts
{#if $error} <div class="err">{$error}</div> {/if}
10. Multi-Language Switcher
<p>{$t('welcome')}</p>
Visual
The Auto-Subscription Hook
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Store (Writable) โ
โ โ โ
โ โโโบ $store (Compiler Directive) โ
โ โ โ โ
โ โ โโโบ Component Template (Re-render) โ
โ โ โ
โ โโโบ Automatic Teardown (On Destroy) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Mutation Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ $store = val โโโบ store.set(val) โ
โ โ โ
โ โโโบ Broadcast to all โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Syntax | $store |
| Mechanism | Compiler-generated subscription |
| Lifecycle | Component-scoped |
| Writing | $store = newVal |
Key takeaways:
- Auto-subscription is syntactic sugar. It hides the complexity of manual subscription/unsubscription behind a simple
$character. - Compiler magic. The Svelte compiler tracks where
$storeis used and generates the necessarysubscribeandunsubscribecalls. - Readable and safe. It prevents common bugs like forgotten unsubscriptions and keeps component templates uncluttered.
- Writable support. The syntax allows you to treat stores as mutable variables, which is convenient for simple app state.
- Migration note. While useful for legacy code, prefer
fromStoreand Runes for new, architecture-heavy Svelte 5 development.
Remember: Auto-subscription is a hallmark of the classic Svelte developer experience. It makes state-driven UIs easy to write and prevents the most common source of state-related bugsโmemory leaks and stale UI referencesโensuring your component remains robust and lightweight.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!