Skip to content

Svelte Stores: State Outside the Component

Svelte stores are a minimal model for state that doesn’t fit into a single component: writable, readable, derived – plus the $ shorthand that subscribes and cleans up on unmount.

≈ 13 min readSoftwareFrontendSvelte

If you install a state management library before the ownership question is settled, you have already paid the price: an extra dependency, a second mental model, and boilerplate – for a problem your project may not even have. The trigger is usually harmless. Two components that aren’t directly related need to share a value; reactivity inside a component works beautifully, but there is no mechanism across the component boundary. From the React world, you know the move of reaching for the big library, and it happens by reflex, even though the real question isn’t an API question: who owns this state, and how much machinery is it allowed to cost?

Svelte already ships with a tool for this case that consists of barely a handful of functions – stores. They answer the ownership question with the smallest possible means and let the cost rise only when a concrete problem forces it. The real gain lies less in the functions themselves than in the discipline they allow: start small and draw the line to “more” deliberately instead of crossing it by reflex.

A store is state that lives outside the component. It doesn’t belong to any single .svelte file but sits in a separate module and can be subscribed to from anywhere. That solves a problem that quickly becomes annoying in component trees: passing values down through several levels just so a deeply nested child can get hold of a piece of information. If you have read my article on Svelte reactivity, you already know the foundation: the compiler builds reactivity in at build time, without a virtual DOM. Stores are the logical continuation of that idea for state that has to cross the component boundary.

Editorial note (July 2026): This text uses the store model of Svelte 3/4. Stores are still supported in Svelte 5 and are especially useful for asynchronous streams or manually controlled subscriptions. For shared state, though, a .svelte.js or .svelte.ts file with runes can be enough today; stores are no longer the only built-in answer outside a component.

The ownership question comes before the tool question#

Before I get to the concrete Svelte functions, one principle that has nothing to do with Svelte itself and applies to every component-based frontend – React, Vue, or Svelte. I derived it in detail for React elsewhere, in the state management comparison, and the core carries over one to one: the deciding question is not “which state library” but “who owns this state?” State belongs at the lowest point where everyone involved can still reach it. As long as that is a single component, it stays there – local, without any ceremony. Only when several unrelated components share the same value, or the value comes from outside the tree, does it leave the component. A global or module-wide store is therefore the exception you justify, not the default you fall into.

Why I stress this so much is a cost argument. Every level I lift state to makes it more expensive: more places that are allowed to write, changes that are harder to trace, a larger surface for bugs. In projects, I have gone the opposite way often enough – first the big library is chosen, then state gets pushed into it until everything is global. The counter-check goes the other way: does this value really need several components, and are they so decoupled that a shared parent component wouldn’t connect them anyway? In my experience, after asking this question, far less global state remains than initially assumed.

To decide whether a value should leave the component, I use three criteria. Reach: do at least two components share it that aren’t in a clean parent-child relationship? Origin: is the value written from outside the tree – a timer, a WebSocket, a sensor? And lifetime: does it have to exist regardless of whether a particular component is currently mounted? If none of these applies, the state stays local, and any solution above that is paid-for complexity with nothing in return. If one applies, a lean, module-wide store is the right answer – in Svelte, literally one line of code. The real work lies in the decision before, not in the API after.

The contract, not the class#

In Svelte, a store is not a special type and not a class you have to inherit from. A store is any object that provides a .subscribe method according to a fixed contract – and optionally a .set method if it should be writable. subscribe must deliver the current value to the subscriber synchronously and return a function for unsubscribing. That contract is what counts. Anything that fulfills it works with the $ syntax.

In practice, you almost never write this .subscribe method yourself. Svelte ships three factory functions that do the work for you. They all come from the same module:

import { writable, readable, derived, get } from 'svelte/store';

The three store types cover three different roles:

  • writable – readable and writable. The default case for shared state that any component or function may change. Provides .set(value), .update(fn), and .subscribe(run).
  • readable – read-only from the outside. The value is set internally via a start callback, ideal for external sources such as a clock, a WebSocket, or an event listener.
  • derived – derived. Computes its value reactively from one or more other stores and updates automatically when one of its sources changes.

The writable store and the $ shorthand#

Let’s start with the most common case – a shared counter that several components use. The store lives in its own module so that every component can import it:

// stores.js
import { writable } from 'svelte/store';

export const count = writable(0);

That is the complete store. One module, one line, one initial value. Now any component can read and write this counter – and this is where Svelte’s most elegant idea comes into play, the $ shorthand:

<script>
  import { count } from './stores.js';
</script>

<button on:click={() => $count++}>
  Clicked {$count} times
</button>

The $count in the template is not a magic global variable but an instruction to the compiler. It recognizes the $ prefix in front of a store reference and generates two things from it: first, a count.subscribe(...) that writes the current value into a local variable and re-renders the template on every change; second – and this is the crucial part – an automatic unsubscribe as soon as the component is destroyed. So you don’t have to take care of cleanup; the compiler does it for you.

Writing is covered by the shorthand, too. The compiler translates $count++ into a count.set(...) call with the incremented value. If you prefer to be more explicit or need a more complex change, you use the methods directly:

<script>
  import { count } from './stores.js';

  function increment() {
    count.update(n => n + 1);
  }

  function reset() {
    count.set(0);
  }
</script>

<button on:click={increment}>+1</button>
<button on:click={reset}>Reset</button>
<p>Current value: {$count}</p>

The difference between set and update is quickly explained. set overwrites the value unconditionally, update receives the current value as an argument and returns the new one – handy whenever the new value depends on the old one.

And now the core of it all: as soon as a second component imports the same store and uses $count, both share the same state. If one changes the value, the other sees it immediately. No prop is passed down the tree, no shared parent component has to hold the state. The store is the shared source that everyone involved hangs on.

graph TD
  S["writable count<br/>(stores.js)"]
  A["Component A<br/>read + write $count"]
  B["Component B<br/>display $count"]
  C["Component C<br/>display $count"]
  S --> A
  S --> B
  S --> C
  A -. "count.set()" .-> S

You can see clearly here what the store does: it decouples the components from each other. A, B, and C don’t have to be related or know about each other. They only know the store.

Derived state with derived#

Often you need a value that follows from another one. You could recompute it in every component – or you derive it once, centrally, and everyone benefits. That is exactly what derived is for:

// stores.js
import { writable, derived } from 'svelte/store';

export const count = writable(0);

export const doubled = derived(count, $count => $count * 2);

doubled is itself a store again, but a read-only one. It has no .set method, because its value follows entirely from count. When count changes, derived recomputes the value and notifies its subscribers. In the component, it then looks just like a regular store:

<script>
  import { count, doubled } from './stores.js';
</script>

<p>{$count} doubled is {$doubled}</p>
<button on:click={() => $count++}>+1</button>

derived can also derive from several sources. In that case, you pass an array of stores and get an array of values in the callback:

import { writable, derived } from 'svelte/store';

export const price = writable(100);
export const quantity = writable(2);

export const total = derived(
  [price, quantity],
  ([$price, $quantity]) => $price * $quantity
);

Besides this synchronous form, there is a second one that receives a set callback. With it, you can set the derived value with a delay or conditionally – for example after a timeout or only once a certain condition is met:

import { derived } from 'svelte/store';

// Sets the value one second after each change of 'count'
export const delayed = derived(
  count,
  ($count, set) => {
    const id = setTimeout(() => set($count), 1000);
    return () => clearTimeout(id);
  }
);

The return value of the callback function here is a cleanup function that Svelte runs before the next computation and on the last unsubscribe. That way, no timeout is left hanging.

readable for external sources#

Not all state is written by the application itself. Sometimes it comes from outside – a clock that ticks, a WebSocket that delivers messages, a sensor. For cases like these, there is readable. From the outside, you can only read it; what feeds it is a start callback that sets up the source:

import { readable } from 'svelte/store';

export const time = readable(null, set => {
  const id = setInterval(() => set(new Date()), 1000);

  return () => clearInterval(id);
});

The timing is worth a close look here, because it reveals a central principle of stores. The start callback doesn’t run immediately when the store is created. It only runs when the first subscriber arrives – when the number of subscribers jumps from zero to one. And the returned function – the stop part – runs when the last subscriber leaves, that is, from one to zero. As long as nobody is listening, no interval ticks and no socket opens for this readable. With writable, set and update stay effective even without subscribers; only an optional start/stop piece of work is lazy. derived, in turn, computes for its subscribers and unsubscribes from its sources when there are none.

In the component, handling it is trivial again, because $time subscribes automatically and cleans up on unmount:

<script>
  import { time } from './stores.js';
</script>

<p>The time is {$time?.toLocaleTimeString()}</p>

The pitfall: subscribe without unsubscribe#

So far, everything ran through the $ shorthand, and there, cleanup is not an issue. But stores aren’t limited to components. You can use them just as well in a plain JavaScript module – in a utility function, a service, anywhere outside of Svelte. And that is exactly where the most common mistake lurks.

Outside a component, there is no $ and no compiler that cleans up. You call subscribe by hand, and the method returns an unsubscribe function. You must keep this function and call it, or you have a leak:

// utils.js
import { count } from './stores.js';

// WRONG: the callback runs forever.
count.subscribe(value => {
  console.log('count is now', value);
});

The return value of subscribe is simply ignored here. As long as the module or this usage context lives, the callback stays registered. The store keeps counting one subscriber, the 1→0 stop callback is never triggered – with a readable that has an interval, the timer would keep running accordingly. This is the right way:

// utils.js
import { count } from './stores.js';

const unsubscribe = count.subscribe(value => {
  console.log('count is now', value);
});

// ... later, when no longer needed:
unsubscribe();

The same rule applies within components, too, if for some reason you use subscribe manually there instead of $: then you have to call the unsubscriber in onDestroy. But honestly, that is almost always a sign that you should simply have used the $ syntax. That bookkeeping is exactly what it takes off your hands.

If you want to read the value only once – without a subscription, without reactivity – there is a clean way that doesn’t let the leak problem arise in the first place:

import { get } from 'svelte/store';
import { count } from './stores.js';

const current = get(count);

get subscribes briefly under the hood, reads the current value, and unsubscribes right away. The value is a snapshot and doesn’t update anymore. That is exactly why get fits well for a one-time read in a JS module – and precisely not in a hot path that runs constantly.

sequenceDiagram
  participant C as First subscriber
  participant S as Store
  participant Q as External source
  C->>S: subscribe(run)
  S->>Q: start callback (0 -> 1)
  Q-->>S: Values flow
  S-->>C: run(value)
  C->>S: unsubscribe()
  S->>Q: stop callback (1 -> 0)

When to use a store, and when not#

The store is the right tool as soon as state no longer fits cleanly into a single component – when several components that aren’t directly related share the same value, or when a value comes from outside the component tree. The classic symptom that calls for a store is prop drilling: you pass a value through three or four levels even though only the bottom component really needs it. A store cuts off this pass-through path. The affected components import the store directly, and the intermediate levels don’t need to know anything about the value.

That leaves the question of whether you also need a big state management library. For the vast majority of Svelte applications: no. The three store types cover a surprising amount. writable for the state you change, derived for everything that follows from it, readable for external sources. That is no compromise, no “good enough for now” – for most real applications, it is simply sufficient. A central store module that exports the individual stores gives the application a clear, manageable structure without you having to drag along another mental model and another dependency.

So where is the edge beyond which you think about more? I would say: only when the state gets truly complex – many interdependent transitions, strict traceability of every change, sophisticated time-travel debugging across a large domain. Requirements like these are rare, and even then you often build a thin layer on top of stores instead of replacing them. But as long as the question is just “How do my components share a value?”, the answer is a store – and you don’t need more.

What remains after several projects with Svelte is less an API recommendation than an order: first determine the owner of the state, then the tool. For the model shown in 2022, writable, readable, and derived are often enough. The $ shorthand handles the subscription bookkeeping in components; outside them, the simple rule remains to pair every manual subscribe with an unsubscribe.

Further reading#

Revised and translated from German with the help of AI.