The "Add Iced Orange" button gets clicked. The cart array does grow, but the number on the page stays at 3. Bugs like this come from misunderstanding reactivity, meaning the page updating by itself when its data changes. In Svelte 5, the answer is $state: only data wrapped in $state (written inside $state(...)) is watched by Svelte.
Picture the kitchen at Mrs. Sri's stall. The cashier writes orders on a board, and the board has a bell that rings by itself every time the writing on it changes. When the bell rings, the cook looks at the board. If the cashier adds a line to the order paper in the drawer instead, the paper does grow, but no bell rings, so the cook never knows. In code, $state is the board with the bell. A plain variable is the paper in the drawer. The cook is Svelte, which updates the page only when the bell rings.
Assignment updates the page
A variable made with $state(...) is component state: data the component remembers and shows in its markup. As soon as that variable gets a new value, the page changes too:
<script>
let count = $state(0)
</script>
<button onclick={() => count += 1}>+1</button>
<p>Count: {count}</p>
| Event | count |
Shows |
|---|---|---|
| Start | 0 | Count: 0 |
| Click +1 | 1 | Count: 1 |
| Click +1 again | 2 | Count: 2 |
$stateis a rune.countstarts at 0, and from then on you read and change it like any plain variable.onclick={...}runs the function inside it every time the button is clicked. Events (things that happen, such as a click) are covered fully in the Event Handling in Svelte lesson.count += 1is an assignment, meaning it gives the variable a new value.count++andcount = count + 1also work, with the same result.- No
setCount(as in React) or other special function. Giving a new value is enough. The code above is also the answer to the first exercise.
What the compiler does
At build time, the compiler reads your code and finds every place a $state variable is read or changed. It replaces each of those places with a call to a small function. From the counter above, Svelte 5.16 produces this code (parts not discussed are replaced by comments):
var on_click = (_, count) => $.set(count, $.get(count) + 1);
// ...
export default function Component($$anchor) {
let count = $.state(0);
// ...
$.template_effect(() => $.set_text(text, `Count: ${$.get(count) ?? ''}`));
// ...
}
$.state(0)makes a box holding a value that Svelte watches.countin your code now points at that box.count += 1becomes$.set(count, $.get(count) + 1).$.getreads what's inside,$.setreplaces it and rings the bell.$.template_effect(...)reads$.get(count), so Svelte notes that the textCount: ...depends oncount. When the bell rings, only this code runs again. It replaces the text node (the piece of text) that holds the number, as in the What is Svelte lesson.- In a component that uses runes, a variable without
$stateisn't turned into$.getand$.set. Changing it rings no bell at all.
In Svelte 5.57, the click handler (the function that runs when the button is clicked) is no longer a separate var on_click. It is written directly inside $.delegated('click', ...). $.state, $.get, $.set and $.template_effect stay the same.
push doesn't trigger an update
Here is the cart at Mrs. Sri's stall, with an array someone forgot to wrap in $state:
<script>
let cart = ["Fried Rice", "Iced Tea", "Chicken Noodles"]
function add() {
cart.push("Iced Orange")
}
</script>
<button onclick={add}>Add Iced Orange</button>
<p>Total: {cart.length}</p>
cart here is a plain array, like the paper in the drawer. push changes its content, but nothing rings the bell, and the compiler doesn't warn either:
| Event | cart in memory |
Shows |
|---|---|---|
| Start | 3 items | Total: 3 |
| Click 1 | 4 items | Total: 3 |
| Click 2 | 5 items | Total: 3 |
The page still reads Total: 3, even though after the first click the array already holds 4 items. The same happens with the other methods that change the array itself (instead of making a new array): pop, shift, splice, sort.
There are two ways to fix it, and both start from $state:
// Way 1: wrap the array in $state, then push as usual
let cart = $state(["Fried Rice", "Iced Tea", "Chicken Noodles"])
function add() {
cart.push("Iced Orange")
}
// Way 2: make a new array and give it to the variable
function add() {
cart = [...cart, "Iced Orange"]
}
- Way 1 is the most direct.
$statewraps arrays and objects in a proxy, an in-between object that records every time its content changes. So afterpush, the page showsTotal: 4right away. The same goes forpop,shift,spliceandsort. - Way 2 also uses a
cartmade with$state.[...cart, "Iced Orange"]copies the old content into a new array, then adds one item. The assignment tocartis what rings the bell. You'll often see thisitems = [...items, newItem]pattern in older code and in React. - Changing content through an index or a property also updates the page, as long as the data was made with
$state. For examplecart[cart.length] = "Iced Orange", ororder.table = 4for an objectorder.
In the second exercise, you use way 1 with let items = $state(["A", "B", "C"]): the Add button runs items.push("D"), and <p>Total: {items.length}</p> changes from Total: 3 to Total: 4. items = [...items, "D"] passes too.
Older code: a plain let that reacts
In Svelte 4 tutorials and repos, the same cart is written like this:
<script>
let cart = ["Fried Rice", "Iced Tea", "Chicken Noodles"]
function add() {
cart.push("Iced Orange")
cart = cart
}
</script>
<button on:click={add}>Add Iced Orange</button>
<p>Total: {cart.length}</p>
- In Svelte 4, every
letat the top level of<script>(not inside a function) is state automatically. The compiler wraps every assignment to it in$$invalidate, and$$invalidateis the bell. In Svelte 5 you write$state(...). - Only assignments get wrapped, so
pushon its own doesn't update the page. That is why older code addscart = cart(an assignment to itself), or usesitems = [...items, newItem]. With$state,pushupdates the page right away, so thecart = cartline isn't needed. on:clickis now writtenonclick.- Svelte 5 still runs a component like this as long as it has no rune at all. Once there is one rune, a plain
letstops reacting (it no longer updates the page), so don't mix the two styles.
⚠️ The data changed, the page didn't
push,pop,spliceorsorton an array that isn't wrapped in$statechange the data, but not the page. Wrap the array:let items = $state([...]).- A derived variable (a variable whose value is calculated from another variable) written with a plain
let, likelet total = cart.length, is only computed once when the component is created. Even whencartis already$state,totalstays 3 as the cart grows. Show{cart.length}directly, or use$derivedfrom the next lesson. - Forgetting
$stateon a number. In a component that uses runes,let count = 0is just a plain variable:count += 1changes its value, but the page stays atCount: 0, and the compiler warnsnon_reactive_update. Writelet count = $state(0).
TL;DR: In Svelte 5, data that changes the page is made with the $state rune (a rune is a special word starting with $): let count = $state(0). Giving it a new value (count += 1, count++) updates the page right away, with no special function like React's setCount. The compiler turns each place that reads count into $.get, and each place that changes it into $.set. $.set is what triggers the page update. Arrays and objects inside $state are wrapped in a proxy, an in-between object that records every change to its content. So push, pop, splice, sort, arr[i] = x and obj.x = y update the page too. Making a new array, as in items = [...items, newItem], works as well. A plain array without $state isn't watched: push changes its content, but the page doesn't change, for example it stays at Total: 3 though the array holds 4. A derived variable (calculated from another variable) written with a plain let is computed only once, so use $derived from the next lesson. Click events are written onclick.
⚡ A new value, and the page follows
Write:
<script>
let count = $state(0)
</script>
<button onclick={() => count += 1}>+1</button>
<p>Count: {count}</p>
Meaning: $state(0) makes count a state that starts at 0. State is data the component remembers and shows. $state is a rune (a special Svelte 5 word starting with $). onclick runs count += 1 every time the button is clicked. Giving count a new value is enough to update the page, with no special function like React's setCount. The compiler turns count += 1 into $.set, which triggers the page update.
⚡ A plain array isn't watched
Write:
<script>
let cart = ["Fried Rice", "Iced Tea", "Chicken Noodles"]
function add() {
cart.push("Iced Orange")
}
</script>
<button onclick={add}>Add Iced Orange</button>
<p>Total: {cart.length}</p>
Guess first: the button is clicked once. Does the page show Total: 3 or Total: 4?
Total: 3. push changes the content to 4 items, but cart isn't $state, so the page isn't updated.
Meaning: Svelte 5 only watches data made with $state. A plain array changes in memory, but the page doesn't change.
⚡ Wrap it in $state, then push
Write:
let cart = $state(["Fried Rice", "Iced Tea", "Chicken Noodles"])
function add() {
cart.push("Iced Orange")
}
Meaning: $state wraps the array in a proxy, an in-between object that records every change to its content. So push, pop, splice and sort update the page right away: after one click, the <p> from the previous step shows Total: 4. Making a new array, cart = [...cart, "Iced Orange"], also updates the page.