Lesson 3 of 9 · 21m
Stores and Shared State: Still Useful, Just Not Everywhere
Writable, readable, and derived stores, when runes are enough, and how to design shared state without recreating a global junk drawer.
Svelte 5 did not make stores useless; it made them optional. Runes are usually better inside component trees because they are explicit and compiler-tracked. Stores remain excellent for shared state that must be subscribed to outside a component, across independently mounted UI, or by non-Svelte JavaScript.
The store contract is tiny
import { writable, derived } from "svelte/store";
export const query = writable("");
export const results = writable([]);
export const empty = derived(
[query, results],
([$query, $results]) => $query.trim().length > 0 && $results.length === 0,
);A store is an object with subscribe. Components can auto-subscribe with the $ prefix:
<script>
import { query, results } from "./search.js";
</script>
<input bind:value={$query} />
{#each $results as result (result.id)}
<a href={result.url}>{result.title}</a>
{/each}The $store syntax subscribes while the component is alive and unsubscribes on destroy. That cleanup discipline is the feature; memory leaks in older Svelte apps often came from manual subscriptions nobody released.
Runes for component state, stores for boundaries
Choose runes when the state belongs to a component or can be passed down with props. Choose a store when:
- a service module publishes state to unrelated parts of the UI,
- imperative code outside Svelte must update or read it,
- you need a small dependency-injection-free integration seam.
Design the ownership, then the syntax
A store named app or data is a junk drawer with a reactive interface. Name domain concepts: presence, cart, playback, alerts. Expose mutation methods for invariants instead of letting every component call update differently:
function createCart() {
const { subscribe, update } = writable([]);
return {
subscribe,
add: (item) => update((items) => [...items, item]),
clear: () => update(() => []),
};
}Field notes
- The
$auto-subscription works in components, not arbitrary utility functions. Read withget(store)sparingly in one-shot imperative code. - A
derivedstore recalculates when inputs publish; avoid expensive unmemoized work in broadly subscribed derived chains. - Do not mirror server cache data into writable stores. Let SvelteKit
loadown server freshness. - If everything is a store, you have global state with extra steps. Push ownership down until sharing is actually required.
Was this lesson helpful?