javascript / intermediate
Snippet
Manual Store Subscriptions and Cleanup
While the $ syntax is common for auto-subscription, understanding manual subscriptions is crucial for complex logic where you need to react to store changes inside functions or outside the markup.
snippet.js
1
2
3
4
5
6
7
8
9
import { count } from './stores.js';import { onDestroy } from 'svelte';let localCount;const unsubscribe = count.subscribe(value => {localCount = value;});onDestroy(unsubscribe);
svelte
Breakdown
1
count.subscribe(value => {...})
Manually listens for changes in the store and returns an unsubscribe function.
2
localCount = value
Updates a local component variable whenever the store value changes.
3
onDestroy(unsubscribe)
Calls the returned function to prevent memory leaks when the component is unmounted.