| | |

Svelte State 03 🧡 Reactive Objects & Class-Based Stores — Encapsulating state, derived getters, and methods inside TypeScript classes

⏱️ Estimated read: 7 min | |

Class-based state management is the ultimate synthesis of object-oriented programming and Svelte’s fine-grained reactivity. By using classes as store containers, you can encapsulate your application state, private mutations, and computed values (via getters) in a single, type-safe entity. In Svelte 5, class properties defined with $state() automatically become reactive, and class getters defined with standard logic function as $derived() values.

This chapter explores how to build these class-based stores. We will cover the lifecycle of reactive fields, the use of private vs. public methods for mutation, and why getters provide a seamless, non-invasive way to expose derived data. This pattern transforms “stores” from opaque, function-heavy objects into transparent, predictable, and highly testable application state managers.

Key point: Reactive class fields marked with $state() behave as observable properties, while class get methods automatically function as reactive derived values; this encapsulation allows you to expose a clean, method-based API for mutations while keeping data integrity strictly enforced within the class.


Why exists

  • The Store-Interface problem. Traditional store patterns (like writable stores) are often just objects you pass around. Classes allow you to define a formal API (e.g., user.login()) that describes exactly how state can be mutated.
  • The Computed-Property problem. Standard objects struggle to hold computed data; class getters provide a natural, read-only interface for data that needs to be calculated on the fly.
  • The Encapsulation problem. By using private class properties (#field), you prevent external code from mutating your state in unexpected ways, enforcing that all changes go through predefined methods.
  • The Testability problem. A class is just a JavaScript object. You can instantiate it in a test suite, call methods, check getters, and verify state without any dependency on the DOM or Svelte’s mounting logic.
  • The Reusability problem. Class-based stores can be inherited, extended, or composed, providing a powerful way to build standard library state for complex features like shopping carts, auth, or filtering.

a. Defining reactive fields in classes

In Svelte 5, you can use $state() directly as a class property. When you define a field this way, Svelte converts the class instance into a reactive proxy. Any component that imports an instance of this class will automatically detect changes to these properties.

class Cart {
  items = $state([]);

  addItem(item) {
    this.items.push(item);
  }
}

This syntax is powerful because it keeps the logic and the data in one place. Unlike old-fashioned stores that required a get() and update() syntax, here you simply interact with standard properties and methods. Svelte tracks these automatically.

b. Getters as derived values

In Svelte 5, class getters are implicitly reactive if they reference $state() properties. They act exactly like $derived() values, automatically re-calculating whenever the underlying state changes. This allows you to expose computed values as simple properties rather than function calls.

class Cart {
  items = $state([]);

  // Implicitly derived
  get total() {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }
}

This is a huge improvement over function-based getters, as it maintains a clean, declarative API for the consumer. The component simply accesses cart.total, and Svelte ensures that the value is always up to date without any extra manual handling.

c. Encapsulation and private mutations

Classes allow for strict control over your data. By using private fields (#name), you ensure that no component can modify your state directly. Instead, they must call your public methods (e.g., user.updateEmail()), which can contain validation logic, side effects, or logging.

class User {
  #email = $state('user@example.com');

  get email() { return this.#email; }

  updateEmail(newEmail) {
    if (newEmail.includes('@')) {
      this.#email = newEmail;
    }
  }
}

This pattern guarantees “data integrity.” You have a single point of failure (the method), which makes debugging trivial. Any mutation of your application’s state is easily traceable to a specific line in your class method, rather than being spread across multiple components.


Complete Example Session

// ============================================
// PART 1: THE STORE CLASS
// ============================================
class TodoStore {
  #todos = $state([]);

  get list() { return this.#todos; }
  get count() { return this.#todos.length; }

  add(text) {
    this.#todos.push({ text, done: false });
  }

  toggle(index) {
    this.#todos[index].done = !this.#todos[index].done;
  }
}

export const todos = new TodoStore();

// ============================================
// PART 2: COMPONENT USAGE
// ============================================
<script>
  import { todos } from './todoStore.ts';
</script>

<button onclick={() => todos.add('New Task')}>Add</button>
<p>Total: {todos.count}</p>
{#each todos.list as todo, i}
  <button onclick={() => todos.toggle(i)}>{todo.text}</button>
{/each}

The session highlights how the class-based store abstracts the array-mutation logic, hides the underlying state, and provides a clear API for components to use.


Quick Reference

Class Reactivity

MemberBehavior
$state fieldReactive data source
get methodReactive derived value
method()Mutation / Side-effect trigger
#privateEncapsulation layer

Why Classes over Plain Objects

AdvantageBenefit
API DesignFormalizes interaction methods
EncapsulationPrevents arbitrary state mutation
InheritanceEnables store composition
OrganizationLogic, Data, and Derived views grouped

Best Practices

✅ Do This:

// Use private fields to protect data
#items = $state([]);                                           // ✅

// Expose data via public getters
get items() { return this.#items; }                            // ✅

// Keep mutation methods descriptive
add(item) { this.#items.push(item); }                          // ✅

❌ Don’t Do This:

// Don't expose state fields directly if validation is needed
items = $state([]); // (Anyone can overwrite)                // ❌

// Don't use setters unless strictly necessary
set items(val) { ... } // (Can make reactivity confusing)   // ❌

// Don't mix logic types
// (Keep side-effects and math logic in methods/getters)       // ❌

Common Pitfalls

PitfallWhy It HappensFix
Losing ReactivityReassigning the class instanceExport a singleton instance
Data OverwritesUsing public fields without private scopeUse #private syntax
Derived InefficiencyExpensive operations in gettersMemoize if extremely complex

Real-World Examples

1. Counter class

class Counter { count = $state(0); inc() { this.count++ } }

2. Auth manager

class Auth { user = $state(null); login(data) { ... } }

3. Form validation

class Form { errors = $state({}); validate() { ... } }

4. Paginated list

class Pager { page = $state(1); next() { this.page++ } }

5. Shopping cart

class Cart { items = $state([]); get total() { ... } }

6. Theme controller

class Theme { mode = $state('light'); toggle() { ... } }

7. Toast manager

class Toasts { items = $state([]); add(t) { ... } }

8. Timer store

class Timer { seconds = $state(0); tick() { this.seconds++ } }

9. Search store

class Search { query = $state(''); get results() { ... } }

10. API Cache

class Cache { data = $state(null); async fetch() { ... } }

Visual

The Encapsulation Boundary

┌──────────────────────────────────────────────┐
│  CLASS INSTANCE                              │
│  ┌────────────────────────┐                  │
│  │ Private State (#)      │                  │
│  └──────────┬─────────────┘                  │
│             │                                │
│      [ Public Method ] ──► Mutate            │
│      [ Public Getter ] ──► Read              │
└──────────────────────────────────────────────┘

Reactive Getters

┌──────────────────────────────────────────────┐
│  State Change ──► Class Field Update         │
│                        │                     │
│  Getter Re-evaluates ◄─┘                     │
│                        │                     │
│  Component UI updates  ◄─┘                   │
└──────────────────────────────────────────────┘

The Class-Store Architecture

┌──────────────────────────────────────────────┐
│  STORE (Class)                               │
│  ┌────────────┐  ┌─────────────┐             │
│  │ State Data │  │ Derived Get │             │
│  └────────────┘  └─────────────┘             │
│        ▲                ▲                    │
│        └────── API ─────┘                    │
└──────────────────────────────────────────────┘

Summary

ItemValue
Reactivity Engine$state / Getter
Scope Protection# private fields
API SurfacePublic methods/getters
ReusabilityClass instance singleton

Key takeaways:

  • Encapsulate by default. Always use # private fields for your internal state to ensure that the class remains the only source of truth for mutation.
  • Use getters for derivation. They are the cleanest, most idiomatic way to expose calculated data in a class-based store.
  • Methods provide the API. Think of your class as an object with a purpose; every public method should correspond to a legitimate user action (e.g., login, addItem, reset).
  • Singletons for global state. Instantiate your class once at the module level to ensure that the state remains consistent across every component that imports it.
  • TypeScript brings reliability. Class stores allow for rich typing and interface enforcement, which is the most reliable way to maintain large application codebases.

Remember: Class-based stores are the professional’s choice for managing Svelte state. They offer a structured, testable, and encapsulated way to handle complex app data that plain objects simply cannot match. By combining the reactive power of Svelte runes with the organizational discipline of TypeScript classes, you create a robust foundation for even the most demanding applications.

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!