$state
\$state is the foundation of Svelte 5 reactivity. It creates a deeply-reactive proxy: mutating a property, pushing into an array, or setting a Map key triggers the right reads downstream.
Primitives, objects, arrays, classes
EXAMPLE
<script>
// Primitive
let count = $state(0);
// Object — every property is reactive
let user = $state({ name: 'Ada', age: 36 });
// Array — push / splice / sort all work
let todos = $state([
{ id: 1, text: 'Learn runes', done: false },
{ id: 2, text: 'Ship the app', done: false },
]);
// Map / Set — reactive too
let counts = $state(new Map());
// Class state — declare in the class
class Cart {
items = $state([]);
get total() {
return this.items.reduce((s, i) => s + i.price, 0);
}
add(item) { this.items.push(item); }
}
let cart = new Cart();
// RAW state — opt out of deep reactivity (better perf for huge objects)
let frozen = $state.raw({ huge: '…' });
</script>
<button onclick={() => count++}>Count: {count}</button>
<input bind:value={user.name}>
<button onclick={() => todos.push({ id: Date.now(), text: 'New', done: false })}>Add</button>
<ul>
{#each todos as t (t.id)}
<li>
<input type="checkbox" bind:checked={t.done}>
<span class:done={t.done}>{t.text}</span>
</li>
{/each}
</ul>
Why it matters
\$state.raw is the escape hatch for huge objects you treat as immutable snapshots — React-style. Skip the proxy overhead when deep reactivity doesn’t earn its keep.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
let count = $state(0); count++; // State is just a variable; assigning re-renders.Try it Yourself »
Discussion
Loading…