Skip to main content

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 with next, 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:
  1. The store/atom value changes (passes comparison check)
  2. For derived stores/atoms, when any dependency changes and the computed value is different
Subscription callbacks are not called immediately upon subscription. Only subsequent changes trigger the callback.

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

Preventing memory leaks is critical. Always call unsubscribe() when you’re done:
Don’t update the same store inside its own subscription:
If you must update a store in a subscription, use guards:
Subscription callbacks should be fast. For expensive operations, debounce or use workers:

Stores

Learn about the store primitive

Atoms

Lower-level reactive primitives

Derived Stores

Create computed state

Batching

Batch updates to reduce subscription calls