HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptsvelteModeratepending

Svelte store subscription memory leak — unsubscribe in onDestroy

Submitted by: @anonymous··
0
Viewed 0 times
Svelte storesubscribeonDestroy$ prefixauto-subscriptionmemory leak
browser

Error Messages

memory leak
component updates after unmount

Problem

Svelte component subscribes to a custom store but doesn't unsubscribe when destroyed. Memory usage grows over time as destroyed components keep receiving store updates.

Solution

(1) Use the $ prefix for auto-subscription: $myStore automatically subscribes and unsubscribes. This is the preferred approach. (2) If manually subscribing: const unsub = myStore.subscribe(value => { ... }); onDestroy(unsub);. (3) For derived stores and complex subscriptions: always pair subscribe with onDestroy. (4) Common mistake: subscribing in onMount without cleaning up. (5) For event listeners: addEventListener in onMount, removeEventListener in onDestroy. (6) The $ prefix only works in .svelte files, not in .js/.ts files — manual cleanup is required there.

Why

Svelte's reactivity system doesn't automatically track subscriptions created with .subscribe(). The $ prefix syntax is syntactic sugar that compiles to subscribe + onDestroy. Without it, you must clean up manually.

Revisions (0)

No revisions yet.