| | |

Svelte 43 🧡 Cross-File Universal Reactivity in .svelte.js and .svelte.ts Modules

⏱️ Estimated read: 7 min | |

In earlier Svelte versions, shared state was typically managed through stores—objects that required manual subscription and unsubscription logic. With the introduction of Runes, Svelte now supports “Universal Reactivity” through .svelte.js and .svelte.ts modules. These files allow you to define reactive state and derived values that exist independently of any component lifecycle, acting as a single source of truth for your entire application.

This chapter covers the creation of reactive state modules, how to import and interact with them from any component, and the mechanics of how Svelte tracks dependencies across file boundaries. We will explore how $state and $derived behave when moved into dedicated JavaScript/TypeScript modules and why this architecture is superior to the traditional store-based approach for most application needs.

Key point: By placing $state and $derived inside a .svelte.js or .svelte.ts file, you create a shared reactive object that maintains its state globally; components importing this module will automatically re-render when the internal state values change, providing seamless state sharing without stores.


Why universal reactivity exists

The store boilerplate problem.

Traditional stores required writable, subscribe, and manually handling the $ prefix or the get() helper. Universal modules eliminate this by allowing you to work with plain variables that happen to be reactive.

The prop-drilling issue.

Passing state through five layers of components just to reach a child is tedious and error-prone. Global state modules allow any component to import the state it needs directly.

Type-safety limitations.

Stores were often difficult to type-check effectively in TypeScript without complex wrappers. Reactive modules are just standard JavaScript/TypeScript files, making full type inference straightforward.

The component coupling trap.

Often, we create a context or store to avoid coupling components, but these tools become complex in their own right. Universal modules decouple the data layer from the view layer entirely.

The lifecycle divergence.

Store subscriptions sometimes led to memory leaks if not handled correctly. Universal reactivity managed by Svelte’s engine ensures that dependencies are tracked automatically, removing the risk of orphaned listeners.


a. Defining reactive state in modules

You can declare state using $state inside any .svelte.js or .svelte.ts file. These variables are reactive by default when exported. When an importing component accesses these variables, Svelte sets up a reactive dependency, ensuring that the component updates whenever the module-level state changes.

// counter.svelte.ts
export let count = $state(0);
export const double = $derived(count * 2);

export function increment() {
  count += 1;
}

This module encapsulates the state and the logic for modifying that state. Because the state is defined in the module scope, it persists for the lifetime of the application, meaning all components importing counter.svelte.ts see the exact same value and logic.

b. Consuming module state in components

Consuming universal state is identical to using local state. You simply import the exported variables. Because Svelte recognizes these are reactive objects, it wraps the access to these variables in a tracking system, triggering a re-render in the component when the underlying value in the module updates.

<script>
  import { count, double, increment } from './counter.svelte.ts';
</script>

<p>Count: {count}</p>
<p>Double: {double}</p>
<button onclick={increment}>Increment</button>

You do not need to use special prefixes or subscribe to the values. The reactivity is “universal” because Svelte handles the wiring behind the scenes, making the distinction between local state and global module state invisible to the developer.

c. Scope and lifecycle management

State defined in a .svelte.js module is effectively a singleton. It is initialized when the module is first evaluated and persists until the page is reloaded. This is perfect for user authentication status, global UI settings, or shared shopping cart data.

// user.svelte.ts
let user = $state({ name: 'Guest', loggedIn: false });

export function login(name: string) {
  user.name = name;
  user.loggedIn = true;
}

export { user };

Because these modules are just JavaScript, you can use standard programming patterns like private variables and getter functions to restrict access, providing a clean API for your state while keeping the internal data protected.


Complete Example Session

// ============================================
// PART 1: THE SHARED STATE MODULE
// ============================================
// theme.svelte.ts
let mode = $state('light');
export const getMode = () => mode;
export const toggle = () => mode = mode === 'light' ? 'dark' : 'light';

// ============================================
// PART 2: IMPORTING STATE
// ============================================
<script>
  import { getMode, toggle } from './theme.svelte.ts';
</script>

// ============================================
// PART 3: DERIVED MODULE STATE
// ============================================
// cart.svelte.ts
export let items = $state([]);
export const total = $derived(items.reduce((acc, i) => acc + i.price, 0));

// ============================================
// PART 4: EFFECT IN MODULE
// ============================================
$effect(() => {
  localStorage.setItem('cart', JSON.stringify(items));
});

The parts above cover module state definition, importing, creating derived values, and using effects inside a module to synchronize with storage.


Quick Reference

API Comparison

FeatureSvelte 4/StoresRunes (.svelte.js)
Statewritable(0)$state(0)
Derivedderived(a, ...)$derived(a * 2)
Subscription.subscribe()Automatic
Syntax$ prefix / get()Direct variable

Module Rules

RuleDescription
File ExtensionMust be .svelte.js / .svelte.ts
PersistenceApp lifetime (Singleton)
ReactivityAutomatic when imported

Best Practices

✅ Do This:

// Group related state in one module
// user.svelte.ts, cart.svelte.ts                   // ✅

// Export functions to modify state
export const inc = () => count++;                   // ✅

// Use derived for computed values
export const total = $derived(sum(items));          // ✅

// Use $effect in modules for side-effects
$effect(() => syncToAPI(state));                    // ✅

❌ Don’t Do This:

// Mutate module state directly from components
// (Use exported functions instead)                 // ❌

// Use stores for everything
// (Use runes for simple state)                     // ❌

// Put non-reactive code in .svelte.js
// Use regular .js for static data                  // ❌

Common Pitfalls

PitfallWhy It HappensFix
No re-renderImporting as static constEnsure using exported $state
Wrong extensionUsing .js instead of .svelte.jsRename file
Unexpected globalState not reset on logoutAdd reset function
Dependency loopModules importing each otherFlatten state architecture

Real-World Examples

1. Global User Session

export let user = $state({ id: null });

2. Shared Shopping Cart

export let cart = $state([]);

3. Theme State

export let theme = $state('dark');

4. Notification Queue

export let notifications = $state([]);

5. Search Filters

export let filters = $state({});

6. Multi-step Form State

export let step = $state(1);

7. Feature Flags

export let flags = $state({ beta: true });

8. WebSocket Status

export let status = $state('offline');

9. Dashboard Layout

export let layout = $state('grid');

10. Translation/Locales

export let lang = $state('en');

Visual

Module-to-Component Reactivity

┌──────────────────────────────────────────────┐
│  .svelte.js Module (The Source)              │
│  export let count = $state(0);               │
│         │                                    │
│         │ (Reactive Link)                    │
│         ▼                                    │
│  Component A    Component B    Component C   │
│  {count}        {count}        {count}       │
└──────────────────────────────────────────────┘

Universal Reactivity Path

┌──────────────────────────────────────────────┐
│  State Mutation ──► Module Variable          │
│                       │                      │
│  Dependency Tracking ─┴─► All Subscribers    │
│                           ▼                  │
│  Component DOM Updates ◄──┘                  │
└──────────────────────────────────────────────┘

Summary

ItemValue
File Type.svelte.js / .svelte.ts
ScopeGlobal / Singleton
Reactivity$state, $derived
SyntaxNative JavaScript
MigrationStores → Runes Modules

Key takeaways:

  • Runes modules are singletons. State defined in .svelte.js persists for the entire application lifecycle, making them perfect for global data.
  • No more subscriptions. You no longer need to call .subscribe() or use the $ prefix; Svelte tracks variables automatically when imported.
  • Logic + State = Module. Keep your state logic inside the module to ensure consistent updates across your entire application.
  • TypeScript ready. Since these are just standard TS files, you get full type safety and IDE autocompletion out of the box.
  • Consistency. Universal reactivity simplifies your architecture by unifying local and global state into a single declarative system.

Remember: Universal reactivity is a fundamental shift in Svelte development. By leveraging .svelte.js modules, you move away from complex, boilerplate-heavy store patterns to a clean, type-safe, and highly performant reactive architecture that feels like standard JavaScript but behaves with Svelte’s legendary efficiency.

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!