How to Use $ Prefix for Store in Svelte: Simple Guide
In Svelte, the
$ prefix is used to auto-subscribe to a store and get its current value reactively inside components. By writing $storeName, Svelte automatically updates the component whenever the store changes, without manual subscription or unsubscribe code.Syntax
The $ prefix is placed before a store variable to access its current value reactively. This syntax works only inside Svelte components.
storeName: The store object created by Svelte'swritableorreadable.$storeName: The current value of the store, auto-updated when the store changes.
This lets you use the store value directly in your markup or script without manual subscriptions.
svelte
<script> import { writable } from 'svelte/store'; const count = writable(0); // In a Svelte component script // Access current count value reactively console.log($count); </script>
Example
This example shows a counter using a writable store and the $ prefix to display and update the count reactively.
svelte
<script> import { writable } from 'svelte/store'; const count = writable(0); function increment() { count.update(n => n + 1); } </script> <button on:click={increment}> Count is {$count} </button>
Output
A button labeled 'Count is 0' initially. Each click increments the number shown after 'Count is' by 1.
Common Pitfalls
Common mistakes when using the $ prefix include:
- Trying to use
$storeoutside a Svelte component script or markup, which causes errors. - Using
$storein regular JavaScript files where Svelte reactivity is not available. - Forgetting that
$storeis read-only; to update, use store methods likesetorupdate.
svelte
/* Wrong: Using $ prefix outside component script */ import { writable } from 'svelte/store'; const count = writable(0); console.log($count); // Error: $count not defined here /* Right: Use inside component script */ <script> import { count } from './store.js'; console.log($count); // Works fine </script>
Quick Reference
| Usage | Description |
|---|---|
| $store | Access current value of the store reactively inside Svelte components |
| store.set(value) | Set the store to a new value |
| store.update(fn) | Update the store value based on current value |
| $store outside component | Causes error, $ prefix works only in Svelte components |
Key Takeaways
Use the $ prefix inside Svelte components to auto-subscribe and get the current store value reactively.
The $store syntax updates your UI automatically when the store changes without manual subscriptions.
You cannot use $store outside Svelte components; it only works in component scripts or markup.
To change store values, use store.set() or store.update(), not the $ prefix.
The $ prefix simplifies reactive code by removing the need for explicit subscribe/unsubscribe calls.