Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 35 ยท State Beyond One Component

Shared State in Modules

Share state between Svelte 5 components using .svelte.js modules: exported objects, classes and getter functions, plus the rules that keep it reactive.

Props work well for parent-child links. But some state belongs to the whole app: the signed-in user, a shopping cart, a theme, a list of notifications. Passing it through ten layers of props is tiring. Svelte 5 gives you a simple answer: put the state in a module and import it wherever it is needed.

The .svelte.js convention

Runes only work in .svelte files and in modules whose file name ends in .svelte.js (or .svelte.ts). A plain .js module is not compiled with runes:

JavaScript
// cart.svelte.js
export const cart = $state({
  items: [],
  coupon: null
});

export function addItem(product) {
  const existing = cart.items.find((i) => i.id === product.id);
  if (existing) {
    existing.qty += 1;
  } else {
    cart.items.push({ ...product, qty: 1 });
  }
}

export function clear() {
  cart.items = [];
}

Any component can import it:

SVELTE
<script>
  import { cart, addItem } from '$lib/cart.svelte.js';
  let count = $derived(cart.items.reduce((n, i) => n + i.qty, 0));
</script>

<button onclick={() => addItem({ id: 1, name: 'Mug' })}>Add mug</button>
<p>{count} items in cart</p>

Every component that reads cart.items updates when it changes, and all of them see the same object because ES modules are evaluated once and shared.

The one rule you must remember

You cannot export a $state variable that you reassign. This fails:

JavaScript
// counter.svelte.js
export let count = $state(0);

export function increment() {
  count += 1; // reassignment: not allowed for an exported state
}

Why: when count is a primitive, importing it copies the value at import time. The compiler cannot make an imported binding live in all places, so it refuses the pattern. You have two good options.

Option 1: export an object and mutate its properties (as cart above):

JavaScript
export const counter = $state({ count: 0 });
export function increment() {
  counter.count += 1;
}

Option 2: keep the state private and export functions (getters):

JavaScript
let count = $state(0);

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

Reading getCount() in a template or $derived is reactive, because it reads the underlying state at call time.

Shared state rules

File name something.svelte.js
Export an object Mutate properties
Or hide it Export getter functions
Not reassigned No exported let count
1 / 2

Classes for richer logic

When state comes with behavior, a class keeps it tidy. Fields declared with $state are reactive, and $derived works as a field too:

JavaScript
// todos.svelte.js
class TodoStore {
  items = $state([]);
  filter = $state('all');

  visible = $derived.by(() => {
    if (this.filter === 'done') return this.items.filter((t) => t.done);
    if (this.filter === 'open') return this.items.filter((t) => !t.done);
    return this.items;
  });

  remaining = $derived(this.items.filter((t) => !t.done).length);

  add(text) {
    this.items.push({ id: crypto.randomUUID(), text, done: false });
  }

  toggle(id) {
    const todo = this.items.find((t) => t.id === id);
    if (todo) todo.done = !todo.done;
  }
}

export const todos = new TodoStore();

Usage: todos.add('Buy milk'), {todos.remaining} left, {#each todos.visible as todo (todo.id)}. Remember to call methods through the object (onclick={() => todos.toggle(id)}) so this stays correct.

Beware shared state on the server

Module-level state is created once per server process. In SvelteKit, one process serves many users, so putting something like the current user in a module variable on the server would leak it across requests. Server-side shared state should come from request-specific places (context, event.locals, load data). Module state is safe for things that are the same for everyone, or things that only exist in the browser. The next lesson shows the safe pattern for per-request, per-tree state.

Reactive built-ins

If your shared state is a Map, Set or Date, use the reactive versions from svelte/reactivity (SvelteMap, SvelteSet, SvelteDate), as covered in deep reactivity.

Stand-in: a shared module

A module is evaluated once, and everyone imports the same object. This stand-in uses an object closure to show two "components" sharing one cart and the primitive-copy problem the rule warns about.

JS One cart, many readers (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two views, one store (stand-in page)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file name lets you use $state in a shared module?

    Only .svelte files and .svelte.js / .svelte.ts modules are compiled with runes.
  2. 2. Why is export let count = $state(0) with count += 1 not allowed?

    Export an object and mutate properties, or export getter functions.
  3. 3. What is a safe way to share a counter across components?

    Objects are proxied and shared by reference, so property changes are seen everywhere.
  4. 4. Why is module-level state risky in server-rendered code?

    Use per-request mechanisms such as context or event.locals for user-specific data.

Summary

  • Put shared state in .svelte.js / .svelte.ts modules and import it anywhere.
  • Do not reassign exported state; export an object (mutate properties) or getter functions.
  • Classes with $state and $derived fields bundle state with behavior.
  • Avoid user-specific module state on the server; use context or request data there.

Next: Context API