0
0
Svelteframework~5 mins

Auto-subscription with $ prefix in Svelte

Choose your learning style9 modes available
Introduction

Auto-subscription with the $ prefix lets you easily use reactive store values in your Svelte components without manually subscribing and unsubscribing.

When you want to display a value from a Svelte store directly in your component.
When you want your component to automatically update when the store value changes.
When you want simpler code without writing subscription logic.
When you want to reactively use store values inside your component's markup or script.
Syntax
Svelte
let value = $storeName;

The $ prefix unwraps the current value of the store.

It automatically subscribes and unsubscribes when the component mounts and unmounts.

Examples
This example shows how to get the current value of a writable store count using $count.
Svelte
import { writable } from 'svelte/store';

const count = writable(0);

// In a Svelte component script
let currentCount = $count;
Here, $time automatically updates currentTime whenever the time store changes.
Svelte
<script>
  import { readable } from 'svelte/store';
  const time = readable(new Date());
  
  // Use auto-subscription
  let currentTime = $time;
</script>
You can also use $name directly in the markup to show the current store value reactively.
Svelte
<script>
  import { writable } from 'svelte/store';
  const name = writable('Alice');
</script>

<p>Hello, {$name}!</p>
Sample Program

This Svelte component uses a writable store count. The $count syntax auto-subscribes to the store and shows the current count. Clicking the button updates the store, and the displayed count updates automatically.

Svelte
<script>
  import { writable } from 'svelte/store';

  const count = writable(0);

  function increment() {
    count.update(n => n + 1);
  }
</script>

<button on:click={increment} aria-label="Increment count">Increment</button>
<p>Count is: {$count}</p>
OutputSuccess
Important Notes

The $ prefix only works inside Svelte components.

It works with any Svelte store type: writable, readable, or derived.

Using $store is cleaner and safer than manual subscriptions.

Summary

The $ prefix unwraps store values automatically in Svelte components.

It keeps your component reactive and updates the UI when the store changes.

It simplifies your code by removing the need for manual subscribe/unsubscribe calls.