$state rune allows you to create reactive state, which means that your UI reacts when it changes.
count is just a number, rather than an object or a function, and you can update it like you would update any other variable.
Signature
The initial value for the state. If not provided, the state will be
undefined.Deep state
If$state is used with an array or a simple object, the result is a deeply reactive state proxy. Proxies allow Svelte to run code when you read or write properties, including via methods like array.push(...), triggering granular updates.
State is proxified recursively until Svelte finds something other than an array or simple object (like a class or an object created with Object.create):
When you update properties of proxies, the original object is not mutated.
Classes
Class instances are not proxied. Instead, you can use$state in class fields (whether public or private), or as the first assignment to a property immediately inside the constructor:
The compiler transforms
done and text into get/set methods on the class prototype referencing private fields. This means the properties are not enumerable.$state.raw
$state.raw.
State declared with $state.raw cannot be mutated; it can only be reassigned:
$state.snapshot
$state proxy, use $state.snapshot:
structuredClone.
$state.eager
await expression, because updates are synchronized.
In some cases, you may want to update the UI as soon as the state changes. For example, you might want to update a navigation bar when the user clicks on a link:
Sharing state across modules
You can declare state in.svelte.js and .svelte.ts files, but you can only export that state if it’s not directly reassigned.
You have two options:
Option 1: Don’t reassign it