Svelte 48 🧡 Custom Store Contracts and Store-to-Rune Migration Patterns
Svelte’s store ecosystem is powerful because of its simplicity: a store is just an object that implements a subscribe method. This “store contract” allows developers to create custom state management solutions that encapsulate complex business logic while adhering to a standard interface. However, as applications evolve toward Svelte 5’s Runes, these custom stores often become technical debt. Understanding how to build these contracts and, more importantly, how to systematically migrate them to reactive class-based models is essential for modernizing your codebase.
This chapter covers the anatomy of a custom store contract, the patterns for building domain-specific state managers, and the architectural strategies for refactoring these stores into modern reactive classes using $state and $derived.
Key point: A custom store is simply an object with a .subscribe method; migration involves replacing this subscription-based interface with reactive class instances where external components track the state directly via Runes instead of listening to a stream of values.
Why custom store contracts exist
The encapsulation of domain logic.
Custom stores allow you to hide the “how” of state updates (e.g., asynchronous API calls, validation, complex calculations) behind a simple, clean API like store.increment() or store.addItem(), keeping the component layer focused on presentation.
Uniform interfaces for diverse state.
By adhering to the store contract, you ensure that any component can interact with your custom state manager exactly like it interacts with a simple writable store, making your components more modular and testable.
Easy integration with legacy patterns.
Because they follow the standard subscribe protocol, custom store contracts work instantly with the legacy {$store} auto-subscription syntax, providing a familiar developer experience during transition periods.
Refactoring safety.
When your logic is wrapped in a store contract, you can change the internal implementation (e.g., switching from local storage to a database sync) without changing a single line of code in the components consuming the store.
The migration pathway.
Custom stores act as the “bridge” to Runes. By defining a clear contract, you create a documented entry point for where the state lives, making it easier to replace the store implementation with a class model later.
a. Anatomy of a store contract
A custom store contract is the minimum interface an object must satisfy to be considered a store: it must provide a subscribe method. This method takes a function and calls it immediately with the current value, and then again whenever that value changes.
function createCustomStore() {
const { subscribe, update } = writable(0);
return {
subscribe,
increment: () => update(n => n + 1),
reset: () => update(() => 0)
};
}
By returning an object with subscribe and custom methods, you create a “store contract.” Any component using {$store} can read the value, while the methods allow the component to perform semantic actions rather than manual mutations.
b. Pattern: The “Rune-Ready” wrapper
When planning a migration, you can write your stores to be “Rune-ready.” This means the internal state is exposed both as a subscribe method for legacy components and as a direct property for Svelte 5 components. This dual-interface design makes the transition period invisible to the rest of the application.
// A store that works for both Svelte 4 and 5
export const counter = {
subscribe: writable(0).subscribe,
value: $state(0), // Rune-ready access
increment() { this.value++; }
};
This allows new components to bypass the subscription boilerplate entirely, while older parts of your application continue to function using the legacy {$counter} syntax.
c. Migration: Stores to Reactive Classes
The migration path involves replacing the subscribe cycle with an instance of a reactive class. Instead of subscribing to a stream of values, the component simply imports an instance of a class and references its $state properties directly.
// From: Custom Store
export const taskStore = createTodoStore();
// To: Reactive Class
export class TaskModel {
tasks = $state([]);
add(t) { this.tasks.push(t); }
}
export const taskModel = new TaskModel();
The key difference is that components now pull data on demand from the class instance via proxy tracking, rather than being pushed data by the store’s subscription callback. This eliminates the “callback hell” of nested subscriptions.
Complete Example Session
// ============================================
// PART 1: LEGACY CUSTOM STORE
// ============================================
function createCounter() {
const { subscribe, update } = writable(0);
return { subscribe, inc: () => update(n => n + 1) };
}
// ============================================
// PART 2: RUNE-READY INTERFACE
// ============================================
class CounterModel {
count = $state(0);
inc() { this.count++; }
// Provide subscription for legacy
subscribe(run) {
run(this.count);
return () => {}; // simplified
}
}
// ============================================
// PART 3: CONSUMPTION (COMPONENT)
// ============================================
<script>
import { counter } from './counter.js';
</script>
<button onclick={() => counter.inc()}>
{counter.count}
</button>
The session shows the evolution from a legacy writable-wrapped object to an encapsulated reactive class model.
Quick Reference
Contract Requirements
| Method | Role |
|---|---|
subscribe | Required by Svelte 4 legacy |
update/set | Standard writable pattern |
custom methods | Domain logic encapsulation |
Migration Checklist
| Step | Action |
|---|---|
| Identify | Locate legacy custom store |
| Wrap | Create reactive class equivalent |
| Proxy | Expose $state as public properties |
| Refactor | Swap {$store} for instance.property |
Best Practices
✅ Do This:
// Encapsulate logic in classes for Svelte 5
class Model { count = $state(0); } // ✅
// Provide a legacy 'subscribe' method if needed
subscribe(run) { return effect(() => run(this.val)); } // ✅
// Prefer direct instance usage over subscriptions
{model.count} // ✅
❌ Don’t Do This:
// Use store.subscribe in new components
// (Use class instance properties instead) // ❌
// Mix store and Rune logic unnecessarily
// (Pick one architecture for a single domain) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Reactivity mismatch | Subscribing to non-reactive prop | Use $state in class |
| Callback hell | Nesting subscriptions | Use reactive class properties |
| Boilerplate | Over-wrapping stores | Simplify to class instances |
Real-World Examples
1. Todo List Logic
class Todo { tasks = $state([]); add(t) { ... } }
2. Auth Session
class Auth { user = $state(null); login(u) { ... } }
3. Cart Management
class Cart { items = $state([]); total = $derived(...) }
4. Settings Manager
class Prefs { theme = $state('light'); }
5. Form Handler
class Form { values = $state({}); errors = $state({}); }
6. Notification Handler
class Notif { list = $state([]); add(n) { ... } }
7. Analytics Tracker
class Analytics { events = $state([]); track(e) { ... } }
8. WebSocket Manager
class Socket { status = $state('closed'); }
9. Paginator
class Pager { page = $state(1); total = $state(10); }
10. Dashboard Stats
class Stats { active = $state(0); }
Visual
The Transition: Store vs. Rune Class
┌──────────────────────────────────────────────┐
│ LEGACY STORE RUNE CLASS │
│ [Subscribe] [Direct Property] │
│ │ │ │
│ Callback Loop ──► Reactive Proxy ◄───────┘
│ │
│ Result: No callbacks, just direct access │
└──────────────────────────────────────────────┘
The Bridge Pattern
┌──────────────────────────────────────────────┐
│ [ Legacy Components ] ──► (subscribe) ──┐ │
│ │ │
│ [ Rune Model ] ◄── (public state) ◄─────┘ │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Store Contract | .subscribe method |
| Modern Pattern | Reactive Class Model |
| Migration Goal | Remove subscription boilerplate |
| State Access | Direct Instance Property |
Key takeaways:
- Contracts provide boundaries. By using custom stores, you isolate your business logic, making it easy to swap or refactor later.
- Runes are a direct evolution. Reactive classes using
$stateare the natural destination for your state management refactoring. - Maintain dual interfaces. During migration, it is often helpful to keep a
subscribemethod in your reactive classes so legacy and modern components can coexist. - Push vs. Pull. Stores “push” values to components via callbacks; Rune classes allow components to “pull” values via proxy-tracked properties.
- Simpler codebases. Eliminating store subscriptions removes a vast amount of boilerplate code and reduces the surface area for bugs.
Remember: Custom stores were a brilliant solution for a world without universal reactivity. In the world of Svelte 5, reactive classes offer the same encapsulation and modularity but with the added benefits of direct property access, better type safety, and no callback hell.
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!