A developer built a custom TypeScript class-based WebSocket library for React after finding existing solutions like react-use-websocket lacking key features. The library uses three core classes: WebsocketConnection (singleton per URL with heartbeat, reconnection, and exponential backoff), WebsocketSubscriptionApi (streaming subscriptions), and WebsocketMessageApi (promise-based request/response). TanStack Store handles reactivity inside the classes, so only components reading specific store slices re-render. Key design decisions include lazy connection opening, shared instances per key to avoid subscribe/unsubscribe churn across page navigation, URI-based message routing, and thin React hook wrappers around the class instances. The post covers the architecture, edge cases like request overwriting and close code handling, and provides a downloadable package.

12m read timeFrom techhub.iodigital.com
Post cover image
Table of contents
Why build it myself?Inspiration: TanStack Form's Class-Based APIsHow the Classes and Hooks Work TogetherPassing Class Instances in ReactTanStack Store in This SetupWhen to Use Which HookConnection Lifecycle: When It Stays Open and When It ClosesEdge Cases Worth KnowingFeature listDownload a copySummary

Sort: