Svelte Stores vs Svelte 5 Runes: Which State Management Approach Should You Use?
Svelte Stores vs Svelte 5 Runes: Which State Management Approach Should You Use?
// stores.ts
import { writable } from 'svelte/store';
export const count = writable(0);
export const user = writable({ name: '', email: '' });<!-- Component.svelte -->
<script>
import { count } from './stores';
</script>
<p>Count: {$count}</p>
<button on:click={() => count.update(n => n + 1)}>Increment</button>import { derived } from 'svelte/store';
import { count } from './stores';
export const doubled = derived(count, $count => $count * 2);<script>
let count = $state(0);
let user = $state({ name: '', email: '' });
</script>
<p>Count: {count}</p>
<button onclick={() => count++}>Increment</button><script>
let count = $state(0);
let doubled = $derived(count * 2);
let message = $derived.by(() => {
if (count > 10) return 'High';
return 'Low';
});
</script><script>
let count = $state(0);
$effect(() => {
console.log('Count changed:', count);
// Cleanup function
return () => console.log('Cleaning up');
});
</script>// counter.svelte.ts
let count = $state(0);
export function getCount() {
return count;
}
export function increment() {
count++;
}Svelte 5 introduced Runes as a new way to handle reactivity, replacing the traditional Svelte Stores approach. This thread compares both systems to help you decide which one fits your project.
Svelte Stores (Svelte 3/4)
Stores have been the standard way to share reactive state across components in Svelte.
Writable Store Example:
// stores.ts
import { writable } from 'svelte/store';
export const count = writable(0);
export const user = writable({ name: '', email: '' });<!-- Component.svelte -->
<script>
import { count } from './stores';
</script>
<p>Count: {$count}</p>
<button on:click={() => count.update(n => n + 1)}>Increment</button>import { derived } from 'svelte/store';
import { count } from './stores';
export const doubled = derived(count, $count => $count * 2);<script>
let count = $state(0);
let user = $state({ name: '', email: '' });
</script>
<p>Count: {count}</p>
<button onclick={() => count++}>Increment</button><script>
let count = $state(0);
let doubled = $derived(count * 2);
let message = $derived.by(() => {
if (count > 10) return 'High';
return 'Low';
});
</script><script>
let count = $state(0);
$effect(() => {
console.log('Count changed:', count);
// Cleanup function
return () => console.log('Cleaning up');
});
</script>// counter.svelte.ts
let count = $state(0);
export function getCount() {
return count;
}
export function increment() {
count++;
}