Svelte 44 ๐งก Reactive Classes and Encapsulated State Models using Runes
In Svelte, while universal modules and simple state objects are powerful, there are scenarios where the logic is inherently object-oriented. Reactive classes provide a robust mechanism to encapsulate data and the methods that manipulate that data into a single, cohesive unit. By using Svelte Runes within class definitions, you can turn standard JavaScript classes into reactive data models that maintain their reactivity even when passed between components.
This chapter explores how to define reactive classes, manage state within class instances, and leverage encapsulation to create domain-specific models. We will look at how the Svelte compiler treats properties marked with $state within a class and how these classes offer a superior alternative to plain objects or store-based architectures for complex UI state management.
Key point: Reactive classes allow you to bundle state and business logic together into instances, providing a clean, encapsulated way to model your application’s domain while ensuring that any component consuming these instances automatically tracks changes to their properties.
Why reactive classes exist
The data-logic coupling problem.
Often, data objects (like a user model or a cart) require specific methods to calculate values or transform data. Plain objects only store values, but reactive classes allow you to attach methods to that state, keeping logic close to the data it influences.
Instance-based state.
While global modules act as singletons, applications often require multiple isolated instances of the same state structureโsuch as multiple independent task boards or separate form configurations. Reactive classes provide a natural blueprint for creating these isolated state containers.
Type-safety and structural integrity.
TypeScript thrives on classes. By defining state in a class, you gain structural guarantees through class interfaces, making it much harder to introduce undefined properties into your application state compared to flexible, loosely defined objects.
Encapsulation and private state.
Reactive classes support private fields (#property). You can keep sensitive state hidden while exposing controlled, reactive public properties, preventing the rest of your app from mutating state in ways that would break your business rules.
Component-agnostic modeling.
Reactive classes can be instantiated outside of the Svelte component tree. You can unit test these models in isolation without ever needing to mount a component, leading to more robust and reliable business logic.
a. Defining Reactive Class Models
When you use $state inside a class property, Svelte transforms that property into a reactive proxy. Unlike standard JavaScript, where instance properties are static, these class properties notify Svelte whenever they are mutated. The compiler handles this proxying automatically, meaning you don’t need to change how you write your methods.
class Task {
id = crypto.randomUUID();
title = $state('');
completed = $state(false);
constructor(title: string) {
this.title = title;
}
}
By defining properties this way, any component that imports the Task class and instantiates it can pass that instance around. Any property accessโlike task.completedโwithin a component template will be tracked as a reactive dependency, ensuring the view updates immediately upon change.
b. Encapsulating Logic with Methods
One of the primary benefits of reactive classes over plain objects is the ability to attach behavior to the data. Methods can perform complex updates to multiple state variables at once, keeping the component templates clean and free from imperative mutation code.
class Cart {
items = $state([]);
add(item) {
this.items.push(item);
}
get total() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}
The get total() method leverages the underlying reactive state of this.items. Because Svelte tracks the use of $state properties inside getters, the computed total value will be automatically re-evaluated whenever the items array is modified, providing a clean API for components to display the total price.
c. Managing Multiple Instances
Because reactive classes are blueprints, you can instantiate as many as you need. This is a common pattern in forms, multi-view dashboards, or lists of items. Each instance maintains its own internal reactive state, completely isolated from other instances of the same class.
// Component usage
let userA = new User('Alice');
let userB = new User('Bob');
// These two instances are entirely reactive and independent
This instance-based approach is often cleaner than managing deep arrays of objects if the object logic is complex. You can even pass instances through props, and Svelte will treat the instance as a single reactive entity, observing updates to any of its $state properties.
Complete Example Session
// ============================================
// PART 1: THE DOMAIN MODEL CLASS
// ============================================
class Note {
content = $state('');
lastUpdated = $state(new Date());
constructor(content) {
this.content = content;
}
update(newContent) {
this.content = newContent;
this.lastUpdated = new Date();
}
}
// ============================================
// PART 2: INSTANTIATION IN COMPONENT
// ============================================
<script>
let myNote = new Note('Hello World');
</script>
<input bind:value={myNote.content} />
<p>Last modified: {myNote.lastUpdated.toLocaleTimeString()}</p>
// ============================================
// PART 3: DERIVED PROPERTIES
// ============================================
class Calculator {
a = $state(0);
b = $state(0);
sum = $derived(this.a + this.b);
}
// ============================================
// PART 4: PRIVATE REACTIVE STATE
// ============================================
class SecureModel {
#secret = $state('hidden');
get secret() { return this.#secret; }
}
These parts show how to build robust models, inject them into components, create reactive derivatives within the class, and hide internal state using private fields.
Quick Reference
Comparison of Patterns
| Pattern | Best For | Behavior |
|---|---|---|
| Reactive Class | Domain Models | State + Methods |
| Reactive Object | Simple State | Data only |
| Module State | Global Singletons | Shared access |
Rule Checklist
| Rule | Requirement |
|---|---|
| Property | Use $state |
| Computed | Use $derived |
| Scope | Instance-based |
| Methods | Public mutation |
Best Practices
โ Do This:
// Initialize reactive state in properties
content = $state(''); // โ
// Use derived inside the class for logic
sum = $derived(this.a + this.b); // โ
// Create separate instances for separate UI sections
let formA = new Form(); let formB = new Form(); // โ
// Keep the class focused on one responsibility
// (Single Responsibility Principle) // โ
โ Don’t Do This:
// Forget to call new for instances
let form = Form(); // Requires 'new' // โ
// Use global module state if you need multiple instances
// (Use classes instead) // โ
// Make everything public
// (Use #private fields for internal logic) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Not reactive | Missing $state | Ensure properties use runes |
| Lost reactivity | Passing class property destuctured | Access via the class instance |
| Confusion | Mutating state outside of methods | Encourage method-based mutations |
| Complexity | Over-using classes for simple data | Stick to plain objects if no logic |
Real-World Examples
1. Todo Item Model
class Todo { title = $state(''); done = $state(false); }
2. Pagination Model
class Pager { page = $state(1); limit = $state(10); }
3. Game Player
class Player { hp = $state(100); score = $state(0); }
4. Form Validator
class Validator { errors = $state({}); valid = $derived(...) }
5. Media Player Instance
class Player { volume = $state(50); playing = $state(false); }
6. Tab Manager
class Tabs { activeIdx = $state(0); }
7. Connection Manager
class Socket { status = $state('init'); }
8. Canvas Drawer
class Drawing { paths = $state([]); }
9. Shopping Cart Item
class Item { qty = $state(1); price = $state(0); }
10. Multi-Step Flow
class Wizard { currentStep = $state(1); }
Visual
The Reactive Class Pattern
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CLASS INSTANCE โ
โ โโโโโโโโโโโโโโโโโโโโโโ โ
โ โ $state properties โ โโโบ [Reactive DOM] โ
โ โ $derived fields โ โ
โ โ Logic Methods โ โ
โ โโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Instance Isolation
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ new Model() โโโบ Instance A (State: 1) โ
โ new Model() โโโบ Instance B (State: 5) โ
โ โ
โ A and B are completely independent โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Model Pattern | Reactive Class |
| Core Rune | $state (Properties) |
| Core Rune | $derived (Computeds) |
| Access | Instance methods |
| Isolation | Per Instance |
Key takeaways:
- Classes bridge state and logic. They are the ideal choice when you need to store data alongside the methods that modify it.
- Instance isolation. Each reactive class instance is an independent reactive state container, perfect for multi-instance requirements.
- Compiler magic. Svelte treats class properties using
$statejust as it does object properties, creating proxy-based reactivity that tracks updates globally. - Type safety. Using classes allows for robust, type-checked data structures, which is an improvement over anonymous objects.
- Single Source of Truth. Encapsulation inside a class keeps your application logic testable and decoupled from the component lifecycle.
Remember: Reactive classes are a sophisticated architectural pattern in Svelte. They allow you to define clear domain models for your app’s state. When you bundle your logic inside these models, your components become purely presentationalโresponsible for rendering the data, while the class instances remain responsible for the “how” and “why” of the application state.
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!