I'm trying to understand the differences and when each is appropriate, especially with Svelte 5's new features.
Great question! Let's break this down clearly to understand when to use $state
vs stores in Svelte 5.
$state
rune:
let variable = $state(initialValue)
Stores (from svelte/store
):
$state
When:Example:
<script>
let count = $state(0); // Simple reactive state
</script>
<button on:click={() => count++}>
Clicks: {count}
</button>
Example:
<script>
import { writable } from 'svelte/store';
const count = writable(0); // Store-based state
function increment() {
count.update(n => n + 1);
}
</script>
<button on:click={increment}>
Clicks: {$count}
</button>
Feature | $state |
Stores |
---|---|---|
Syntax | Simpler | More verbose |
Reactivity | Automatic, granular | Requires explicit subscription |
Async handling | Less suited | Better suited |
Sharing across files | Use .svelte.js file |
Use Context API |
Legacy support | Svelte 5+ only | All versions |
/// file: sharedState.svelte.js
export const appState = $state({
count: 0,
user: 'Guest'
});
<script>
let localCount = $state(0); // Local component state
</script>
<script>
import { writable } from 'svelte/store';
const asyncData = writable(null);
function fetchData() {
// Complex async logic here
}
</script>
In Svelte 5, prefer $state
for most cases due to its simplicity and power. Use stores when you need:
Remember that $state
and stores can coexist in the same project - use the right tool for each specific scenario.