| | |

Svelte 44 ๐Ÿงก Reactive Classes and Encapsulated State Models using Runes

โฑ๏ธ Estimated read: 7 min | |

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

PatternBest ForBehavior
Reactive ClassDomain ModelsState + Methods
Reactive ObjectSimple StateData only
Module StateGlobal SingletonsShared access

Rule Checklist

RuleRequirement
PropertyUse $state
ComputedUse $derived
ScopeInstance-based
MethodsPublic 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

PitfallWhy It HappensFix
Not reactiveMissing $stateEnsure properties use runes
Lost reactivityPassing class property destucturedAccess via the class instance
ConfusionMutating state outside of methodsEncourage method-based mutations
ComplexityOver-using classes for simple dataStick 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

ItemValue
Model PatternReactive Class
Core Rune$state (Properties)
Core Rune$derived (Computeds)
AccessInstance methods
IsolationPer 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 $state just 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.

Was this helpful?


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!