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