Svelte • Legacy APIs

Reactive let/var declarations

In runes mode, reactive state is explicitly declared with the $state rune.

In legacy mode, variables declared at the top level of a component are automatically considered reactive. Reassigning or mutating these variables (count += 1 or object.x = y) will cause the UI to update.

<script lang="ts">
	let let count: numbercount = 0;
</script>

<button on:click={() => let count: numbercount += 1}>
	clicks: {let count: numbercount}
</button>
<script>
	let let count: numbercount = 0;
</script>

<button on:click={() => let count: numbercount += 1}>
	clicks: {let count: numbercount}
</button>

Because Svelte’s legacy mode reactivity is based on assignments, using array methods like .push() and .splice() won’t automatically trigger updates. A subsequent assignment is required to ‘tell’ the compiler to update the UI:

<script lang="ts">
	let let numbers: number[]numbers = [1, 2, 3, 4];

	function function (local function) addNumber(): voidaddNumber() {
		// this method call does not trigger an update
		let numbers: number[]numbers.Array<number>.push(...items: number[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@paramitems New elements to add to the array.
push
(let numbers: number[]numbers.Array<number>.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

length
+ 1);
// this assignment will update anything // that depends on `numbers` let numbers: number[]numbers = let numbers: number[]numbers; } </script>
<script>
	let let numbers: number[]numbers = [1, 2, 3, 4];

	function function (local function) addNumber(): voidaddNumber() {
		// this method call does not trigger an update
		let numbers: number[]numbers.Array<number>.push(...items: number[]): number

Appends new elements to the end of an array, and returns the new length of the array.

@paramitems New elements to add to the array.
push
(let numbers: number[]numbers.Array<number>.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

length
+ 1);
// this assignment will update anything // that depends on `numbers` let numbers: number[]numbers = let numbers: number[]numbers; } </script>