Skip to main content

Overview

The withConnectHook 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
Returns:
  • void: No cleanup needed
  • () => void: Cleanup function to run on disconnect
  • Promise<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