Skip to main content

Often, you will need to derive state from other state. For this, we have the $derived rune:

App
let numbers = $state([1, 2, 3, 4]);
let total = $derived(numbers.reduce((t, n) => t + n, 0));

We can now use this in our markup:

App
<p>{numbers.join(' + ')} = {total}</p>

The expression inside the $derived declaration will be re-evaluated whenever its dependencies (in this case, just numbers) are updated. Unlike normal state, derived state is read-only.

Edit this page on GitHub

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