Skip to main content

As we saw in the previous exercise, state reacts to reassignments. But it also reacts to mutations — we call this deep reactivity.

Make numbers a reactive array:

App
let numbers = $state([1, 2, 3, 4]);

Now, when we change the array...

App
function addNumber() {
	numbers[numbers.length] = numbers.length + 1;
}

...the component updates. Or better still, we can push to the array instead:

App
function addNumber() {
	numbers.push(numbers.length + 1);
}

Deep reactivity is implemented using proxies, and mutations to the proxy do not affect the original object.

Edit this page on GitHub

previous next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
	let numbers = [1, 2, 3, 4];
 
	function addNumber() {
		// TODO implement
	}
</script>
 
<p>{numbers.join(' + ')} = ...</p>
 
<button onclick={addNumber}>
	Add a number
</button>