Skip to main content

Subscription

The Subscription type represents a subscription to an atom’s changes. It provides a method to unsubscribe and stop receiving updates.

Type Definition

Properties

unsubscribe

Unsubscribes from the atom and stops receiving updates. After calling this method, the observer will no longer be notified of changes. Type:

Usage Examples

Basic subscription and cleanup

Multiple subscriptions

Cleanup in useEffect (React)

Conditional subscription

Collecting multiple subscriptions

Auto-unsubscribe after condition

Temporary subscription

Best Practices

  1. Always unsubscribe: Remember to call unsubscribe() when you no longer need updates to prevent memory leaks
  2. Cleanup in effects: In React or similar frameworks, return the unsubscribe function from your effect cleanup
  3. Store subscriptions: Keep references to subscriptions you might need to cancel later
  4. Multiple subscriptions: You can have multiple subscriptions to the same atom; each needs to be unsubscribed independently
  • Observer - The observer interface used when subscribing
  • Atom - The writable atom type that returns subscriptions
  • ReadonlyAtom - The read-only atom type that returns subscriptions