Skip to main content
Basic Svelte
Introduction
Reactivity
Props
Logic
Events
Bindings
Classes and styles
Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

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>