What are Subscriptions?
Subscriptions allow you to react to changes in stores and atoms. When you subscribe to a store or atom, your callback function is called whenever the value changes, enabling you to synchronize external systems, update UI, trigger side effects, and more.Basic Subscriptions
Subscribe to a Store
Subscribe to an Atom
Subscription API
Function Signature
Using an Observer Object
For more control, you can pass an observer object withnext, error, and complete handlers:
The
error and complete callbacks are currently not used by the core library but are provided for RxJS interoperability.When Subscriptions Fire
Subscriptions fire when:- The store/atom value changes (passes comparison check)
- For derived stores/atoms, when any dependency changes and the computed value is different
Unsubscribing
Always unsubscribe when you’re done to prevent memory leaks:Automatic Cleanup Pattern
Multiple Subscriptions
You can have multiple subscriptions to the same store or atom:Subscribing to Derived Stores
You can subscribe to derived stores just like regular stores:Practical Examples
Sync to LocalStorage
Update Document Title
Log State Changes
Debounced Subscription
React to Specific Changes
Analytics Tracking
Sync Multiple Stores
Form Validation Feedback
Subscriptions vs Derived Stores
When should you use a subscription versus a derived store?Use Subscriptions For
- Side effects (API calls, logging)
- Syncing to external systems
- Imperative updates (DOM, localStorage)
- One-way data flow triggers
Use Derived Stores For
- Pure computations
- Derived state
- Data transformations
- Reactive data flow
Best Practices
Always Unsubscribe
Always Unsubscribe
Preventing memory leaks is critical. Always call
unsubscribe() when you’re done:Avoid Infinite Loops
Avoid Infinite Loops
Don’t update the same store inside its own subscription:
Use Guards for Conditional Updates
Use Guards for Conditional Updates
If you must update a store in a subscription, use guards:
Keep Callbacks Fast
Keep Callbacks Fast
Subscription callbacks should be fast. For expensive operations, debounce or use workers:
Related Concepts
Stores
Learn about the store primitive
Atoms
Lower-level reactive primitives
Derived Stores
Create computed state
Batching
Batch updates to reduce subscription calls