Handling State Updates in Svelte
By Flavio Copes
Learn how Svelte 5 handles state updates with $state, plain assignments like count++, and how array mutations work with runes versus older Svelte versions.
One great thing about Svelte is that you don’t need to do anything special to update the state of a component.
All you need is an assignment.
In Svelte 5, declare that state with $state. Say you have a count variable. You can increment it with count = count + 1, or count++:
<script>
let count = $state(0)
const incrementCount = () => {
count++
}
</script>
{count} <button onclick={incrementCount}>+1</button>
This is nothing groundbreaking if you are unfamiliar with how modern Web frameworks handle state, but in React you’d have to either call this.setState(), or use the useState() hook.
Vue 3 wraps values with ref() or reactive() so the framework can track them.
Having used both, I find Svelte to be a much more JavaScript-like syntax.
With $state, objects and arrays are deeply reactive. You can use methods that change the array in place, like push(), and Svelte still updates the UI:
let list = $state([1, 2, 3])
list.push(4)
You can also reassign with the spread operator if you prefer that style:
let list = $state([1, 2, 3])
list = [...list, 4]
Legacy note: Svelte 3 and 4
In Svelte 3 and 4, and in Svelte 5 components that don’t use runes (what Svelte calls legacy mode), a plain let list = [1, 2, 3] was not a proxy. Methods like push() changed the array, but Svelte did not notice unless you reassigned:
let list = [1, 2, 3]
list.push(4)
list = list
That reassignment trick is for legacy mode. New components should use $state.
Want me to talk about your product? You can sponsor this site.