Working with Javascript and Rune reactivity

With runes, reactivity extends beyond the boundaries of your .svelte files.

<script>
	import { createCounter } from './counter.svelte.js';
	
	const counter = createCounter();
</script>

<button on:click={counter.increment}>
	clicks: {counter.count}
</button>

counter.svelte.js

In counter.svelte.js we created a reactive piece of state called count using $state(0) and it returns two usable functions:

get count() { return count }
  • This is a getter function for the count property.

  • When you access the count property on the returned object, this getter function is invoked, and it returns the current value of the count state.

  • This allows you to retrieve the current value of count as if it were a regular property, but behind the scenes, it is dynamically pulling the latest reactive state.

increment: () => count += 1
  • This is an arrow function that increments the value of count by 1.

  • Since count is reactive, any part of your Svelte component that depends on count will automatically update when this method is called.

App.svelte

First the javascript code is imported, and assigned to a variable. Then we can access those returned functions using the dot . to access them.

Outside .svelte components, runes can only be used in .svelte.js and .svelte.ts modules.

Last updated