Auto-subscriptions

The app in the previous example works, but there’s a subtle bug — the unsubscribe function never gets called. If the component was instantiated and destroyed many times, this would result in a memory leak.

One way to fix it would be to use the onDestroy lifecycle hook:

  1. <script>
  2. import { onDestroy } from 'svelte';
  3. import { count } from './stores.js';
  4. import Incrementer from './Incrementer.svelte';
  5. import Decrementer from './Decrementer.svelte';
  6. import Resetter from './Resetter.svelte';
  7. let count_value;
  8. const unsubscribe = count.subscribe(value => {
  9. count_value = value;
  10. });
  11. onDestroy(unsubscribe);
  12. </script>
  13. <h1>The count is {count_value}</h1>

It starts to get a bit boilerplatey though, especially if your component subscribes to multiple stores. Instead, Svelte has a trick up its sleeve — you can reference a store value by prefixing the store name with $:

  1. <script>
  2. import { count } from './stores.js';
  3. import Incrementer from './Incrementer.svelte';
  4. import Decrementer from './Decrementer.svelte';
  5. import Resetter from './Resetter.svelte';
  6. </script>
  7. <h1>The count is {$count}</h1>

Auto-subscription only works with store variables that are declared (or imported) at the top-level scope of a component.

You’re not limited to using $count inside the markup, either — you can use it anywhere in the <script> as well, such as in event handlers or reactive declarations.

Any name beginning with $ is assumed to refer to a store value. It’s effectively a reserved character — Svelte will prevent you from declaring your own variables with a $ prefix.