In Svelte 5, the introduction of runes like $state
has changed how we manage state. Let me explain when to use each approach and why:
$state
Use $state
for most reactive state management needs. It's simpler and more intuitive than stores because:
Example:
<script>
// Simple counter with $state
let count = $state(0);
</script>
<button on:click={() => count++}>
Clicks: {count}
</button>
Stores are still useful in specific scenarios:
Example store usage:
<script>
import { writable } from 'svelte/store';
// Store-based counter
const count = writable(0);
</script>
<button on:click={() => $count++}>
Clicks: {$count}
</button>
Feature | $state |
Stores |
---|---|---|
Syntax | Simpler (just variables) | More complex API |
Reactivity | Automatic | Manual subscription |
Deep reactivity | Built-in | Requires custom solutions |
Async handling | Basic | More powerful |
Cross-component | Via props or context | Via context or imports |
Learning curve | Lower | Higher |
$state
: For most cases, start with $state
as it's simpler and more intuitive$state
object in a separate file$state
's automatic deep reactivity is often betterExample of shared state with $state
:
// state.svelte.js
export const userState = $state({
name: 'John',
preferences: {
theme: 'dark',
notifications: true
}
});
Remember: The choice between $state
and stores isn't always clear-cut. Start simple with $state
, and only use stores when you encounter limitations or specific needs that $state
can't handle well.