Overview
ThewithConnectHook extension executes a callback when the atom gains its first subscriber (connects) and optionally runs cleanup when the last subscriber disconnects. This is perfect for managing resources, subscriptions, or side effects that should only exist while the atom is actively being used.
Type Signature
Parameters
function
required
Callback executed when the atom connects (gains first subscriber).Parameters:
target: The atom being connected
void: No cleanup needed() => void: Cleanup function to run on disconnectPromise<void | (() => void)>: Async initialization with optional cleanup
Examples
Basic Connection Tracking
Cleanup on Disconnect
WebSocket Connection
Async Initialization
Multiple Subscribers
Computed Dependency Chain
Abort on Disconnect
Resource Management
Use Cases
Server-Sent Events (SSE)
Database Subscription
Analytics Tracking
Geolocation Tracking
Event Bus Subscription
Reactive Resize Observer
Pattern: Circular Subscriptions
Related
- withChangeHook - React to state changes
- withDisconnectHook - Shorthand for disconnect-only hook
- subscribe - Subscribe to atom changes