Svelte State 10 🧡 Legacy Store Interoperability — Migrating writable/readable/derived stores to Runes and bridging with toStore() / fromStore()
In the transition to Svelte 5, the new reactive primitives—$state, $derived, and $effect—have superseded the legacy store pattern. While Runes offer superior ergonomics, performance, and granularity, many existing Svelte applications and external libraries rely heavily on the writable, readable, and derived store contracts. Svelte 5 provides a robust interoperability layer to bridge these two worlds, allowing you to gradually migrate your codebase without breaking existing functionality.
Bridging these patterns is essential for “hybrid” applications where you might introduce Runes into a specific feature while keeping a global store-based authentication system or using third-party libraries that expect store objects. By understanding how to move data between these reactive systems, you can maintain a unified reactive flow regardless of the underlying implementation details.
This chapter covers the migration path from legacy stores to Rune classes and provides the technical blueprints for using fromStore() and toStore() to keep legacy interfaces compatible with modern reactive state.
Key point: Legacy stores are event-based objects that require subscription management, whereas Runes are reactive primitives that Svelte manages automatically; use fromStore() to treat a store as a read-only $state rune, and toStore() to wrap a rune in a store contract for legacy API compatibility.
Why store-to-rune interoperability exists
The legacy migration path. Most large applications cannot be rewritten in a single pass. Interoperability allows teams to adopt Runes for new features while maintaining stability in legacy parts of the system.
Third-party ecosystem compatibility. Many UI component libraries or state-management utilities still expect the standard subscribe method of the Svelte store contract. toStore() bridges modern Rune state into these existing interfaces.
The shift from “event-driven” to “signal-driven”. Legacy stores rely on consumers calling subscribe() to receive updates. Runes rely on Svelte’s internal tracking graph. Interop functions manage the translation between these two execution models.
Avoiding manual subscription overhead. By using fromStore(), you avoid the need to manually call unsubscribe() in component lifecycle hooks, as the integration automatically cleans up when the Rune’s scope is destroyed.
Granular reactivity vs. object-level updates. Legacy stores often force an entire object update to trigger reactivity. Runes allow for granular property-level reactivity. Bridging helps when you need to “pipe” specific bits of legacy state into a more efficient Rune-based calculation.
a. Migrating legacy stores to Rune classes
The best practice for migrating is to encapsulate legacy store logic into a Rune-based class. Instead of a writable, you define a class with $state properties. This not only makes the state more readable but also unlocks the ability to define derived state using $derived rather than complex derived() function chains.
// ❌ Legacy store
export const count = writable(0);
// ✅ Rune-based class
export class Counter {
count = $state(0);
increment() { this.count++; }
}
The migration involves moving your store’s “actions” (the functions that modify the store) into class methods. This creates a cleaner API surface where the state and the logic that modifies it are physically collocated.
b. Bridging stores into Runes with fromStore()
fromStore() allows you to consume a legacy store as if it were a modern Rune. When you pass a store into fromStore(), Svelte creates a reactive snapshot of that store’s value. Whenever the store updates, the resulting Rune is automatically updated. This is perfect for when you want to use a global store value inside a modern component logic.
import { fromStore } from 'svelte/store';
import { legacyStore } from './stores';
// The store is now a reactive rune
let count = fromStore(legacyStore);
// Accessing the value
$effect(() => console.log(count.current));
The returned object has a .current property that tracks the value. Because it is a Rune, it is fully compatible with $derived and $effect, making it easy to incorporate legacy data into your modern reactive graph.
c. Exposing Runes to legacy systems with toStore()
If you have a modern Rune-based state but need to pass it to a legacy component that expects a store, use toStore(). This function takes a getter function (a callback that returns the Rune value) and returns an object that implements the standard subscribe method.
import { toStore } from 'svelte/store';
let myState = $state({ user: 'Alice' });
// Create a store for legacy compatibility
let store = toStore(() => myState.user);
// Now 'store' can be used in old components: $store
toStore() essentially creates a “subscriber wrapper.” Whenever the Rune value inside your getter changes, the store notifies all its legacy subscribers, ensuring your modern state continues to drive the legacy parts of your application seamlessly.
Complete Example Session
// ============================================
// PART 1: LEGACY STORE
// ============================================
import { writable } from 'svelte/store';
export const legacyStore = writable(0);
// ============================================
// PART 2: IMPORTING TO RUNES
// ============================================
import { fromStore } from 'svelte/store';
let count = fromStore(legacyStore);
// Access as count.current
// ============================================
// PART 3: EXPORTING RUNES TO STORE
// ============================================
import { toStore } from 'svelte/store';
let runeState = $state(0);
let store = toStore(() => runeState);
// ============================================
// PART 4: RUNE CLASS MIGRATION
// ============================================
class Settings {
theme = $state('dark');
toggle() { this.theme = this.theme === 'dark' ? 'light' : 'dark'; }
}
This sequence covers the complete lifecycle of interoperability, from consuming old stores to exposing new state.
Quick Reference
Interop Primitives
| Function | Input | Output | Usage |
|---|---|---|---|
fromStore | Store | Rune | Consume store in Runes |
toStore | Getter | Store | Expose Rune to legacy |
Migration Path
| Feature | Legacy Store | Rune Class |
|---|---|---|
| State | writable | $state |
| Derived | derived() | $derived() |
| Actions | exported functions | class methods |
Best Practices
✅ Do This:
let count = fromStore(legacyStore); // ✅
let store = toStore(() => runeState); // ✅
// Use class methods for state updates
class Auth { user = $state(); login() { ... } } // ✅
❌ Don’t Do This:
// Manually subscribing in components
legacyStore.subscribe(v => val = v); // ❌
// Exporting writable from new files
export const state = writable(0); // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Not reactive | Forgetting .current | Use count.current |
| Missing updates | toStore getter static | Ensure getter returns Rune |
| Memory leaks | Store subscriptions | Use fromStore (auto-clean) |
| Type issues | toStore generic | toStore<T>(() => ...) |
Real-World Examples
1. Consuming Global Store
let user = fromStore(authStore);
2. Exposing State for Legacy UI
let store = toStore(() => state.value);
3. Migration Wrapper
export class Counter {
val = $state(0);
// bridge to existing store
sync(s) { return toStore(() => this.val); }
}
4. Readable Bridge
let readable = fromStore(someReadable);
5. Complex Derived Store
let derived = toStore(() => state.a + state.b);
6. Cleaning Up
// fromStore handles cleanup automatically
7. Property Access
console.log(count.current);
8. Legacy Component usage
{$legacyBridge}
9. Class Injection
const instance = new Settings();
10. Type Inference
let s = toStore<number>(() => val);
Visual
Store to Rune (Consumption)
┌──────────────────────────────────────────────┐
│ Legacy Store ──► fromStore() ──► Rune │
│ │
│ - Reactive snapshot │
│ - Automatic subscription management │
└──────────────────────────────────────────────┘
Rune to Store (Exposure)
┌──────────────────────────────────────────────┐
│ Rune State ──► toStore() ──► Legacy Store │
│ │
│ - Notifies legacy subscribers │
│ - Drive legacy UI via $store │
└──────────────────────────────────────────────┘
The Migration Path
┌──────────────────────────────────────────────┐
│ Store (writable) ──► Class ($state) │
│ │
│ - Move actions to methods │
│ - Replace derived() with $derived │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
fromStore | Store to Rune |
toStore | Rune to Store |
| Migration Goal | Rune-based classes |
| Store API | .subscribe / .set |
| Rune API | $state / .current |
Key takeaways:
- Use
fromStore()to consume stores. It creates a reactive snapshot that integrates seamlessly with your modern Rune-based logic without manual subscription management. - Use
toStore()for legacy compatibility. If you must pass modern state to a library or component that expects a store, wrap it in a getter usingtoStore(). - Migrate to Rune-based classes. Encapsulating state in classes is the cleanest way to move from legacy stores, as it co-locates data and logic.
- Bridge incrementally. You don’t need a total rewrite; use the interop functions to migrate piece-by-piece while maintaining a working application.
- Leverage automatic cleanup. Modern interop functions handle subscription lifecycles, reducing the risk of memory leaks associated with manual
subscribeusage.
Remember: Interoperability is a bridge, not a permanent destination. Use these tools to maintain stability during your migration to Svelte 5, but keep your long-term goal as the clean, class-based Rune architecture that avoids the extra overhead of the store contract entirely.
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!