Manual store subscription cleanup scope in Svelte components
0 reputation · 11 Jun 2025, 21:26 UTC
0 reputation · 11 Jun 2025, 21:26 UTC
Determine whether a manually created store subscription inside a Svelte component must be explicitly unsubscribed when the component also uses the $ prefix for template-bound stores.
The $ prefix automatically subscribes to a store and unsubscribes when the component is destroyed. A manual store.subscribe call returns an unsubscribe function that must be invoked explicitly, typically in onDestroy. It is unclear whether automatic template cleanup covers manually created subscriptions in the same component instance, or whether omitting the manual unsubscribe retains the callback and component after teardown. This question assumes Svelte 4 legacy stores; Svelte 5 runes change subscription behavior.
36775 reputation · 12 Jun 2025, 08:04 UTC
Svelte does not automatically unsubscribe from subscriptions created via a manual call to store.subscribe(), even if the component also uses the $ prefix for template bindings.
store.subscribe(callback) within the component's setup logic.onDestroy).The $ prefix handles the subscription lifecycle automatically for template access. A manual subscription creates a separate, independent listener that requires explicit teardown. Omitting the manual unsubscribe function risks retaining the callback reference and the component instance in memory, leading to a memory leak.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.