Registry / messaging / react-realtime-hooks

react-realtime-hooks

JSON →
library2.0.2jsnpmunverified

A production-ready React library providing composable hooks for WebSocket and Server-Sent Events (SSE) with auto-reconnect, heartbeat, typed connection states, and browser network awareness. Current stable version is 2.0.2, released in 2024, with a release cadence of approximately monthly. Key differentiators include discriminated connection snapshots (idle, connecting, open, reconnecting, closing, closed, error), exponential backoff with jitter, heartbeat with ack matching and latency measurement, environment-aware connection gating for offline state and background tabs, and zero runtime dependencies beyond React. Ships TypeScript types, supports React 18+, and is SSR- and Strict Mode-safe.

npm install react-realtime-hooks
INSTALL
IMPORT
SIG · REACT-REALTIME-HOO
R
react-realtime-hooks
messagingjavascriptv2.0.2
harness data pending
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

useWebSocket
import { useWebSocket } from 'react-realtime-hooks'
import useWebSocket from 'react-realtime-hooks'
Named export, not default. TypeScript: generic type can be passed like useWebSocket<MyMessageData>(url).
useEventSource
import { useEventSource } from 'react-realtime-hooks'
const useEventSource = require('react-realtime-hooks').useEventSource
ESM-only package. CommonJS require will throw an error. Use dynamic import or ESM in Node/Next.js.
ConnectionState
import { ConnectionState } from 'react-realtime-hooks'
import { ConnectionState } from 'react-realtime-hooks/dist/types'
Type export for the discriminated union of connection states. Includes values: 'idle', 'connecting', 'open', 'reconnecting', 'closing', 'closed', 'error'.
useConnectionGate
import { useConnectionGate } from 'react-realtime-hooks'
import { useConnectionGate } from 'react-realtime-hooks/gate'
Same entry point as other hooks. No sub-path exports.

Shows a React component using useWebSocket with reconnection, heartbeat, and connection gating from useConnectionGate. Includes TypeScript typing for send and parse messages.

import React from 'react'; import { useWebSocket, useConnectionGate, ConnectionState } from 'react-realtime-hooks'; const WS_URL = process.env.REACT_APP_WS_URL ?? 'wss://echo.websocket.org'; export const RealtimeComponent: React.FC = () => { const { connectionGate } = useConnectionGate({ online: true, visible: true }); const { status, send, lastMessage, reconnect, close, open } = useWebSocket(WS_URL, { reconnect: { attempts: Infinity, delay: 1000, maxDelay: 30000, jitter: true, }, heartbeat: { interval: 30000, timeout: 5000, }, onOpen: () => console.log('Connected'), onMessage: (event) => console.log('Message:', event.data), onError: (event) => console.error('Error:', event), onClose: (event) => console.log('Closed:', event.code), connect: connectionGate, parseMessage: (data) => JSON.parse(data), serializeMessage: (msg) => JSON.stringify(msg), }); const sendMessage = () => { send({ type: 'greeting', content: 'Hello!' }); }; return ( <div> <p>Status: {status}</p> <button onClick={sendMessage} disabled={status !== 'open'}>Send</button> <button onClick={reconnect}>Reconnect</button> <button onClick={close}>Close</button> <button onClick={open}>Open</button> {lastMessage && <p>Last message: {lastMessage.data}</p>} </div> ); };
Debug
Known issues
breakingIn v2.0.0, the API changed from returning a single object with multiple properties to returning individual named exports per hook. Also, the heartbeat mechanism was redesigned to support ack matching and latency measurement, which may break existing heartbeat configurations.
fix
Update imports and hook usage to match new API. Refer to the migration guide in the GitHub repository. For heartbeat, use the new 'heartbeat' option object instead of previous callback-based approach.
affects: >=2.0.0
breakingIn v2.0.0, the package became ESM-only and no longer supports CommonJS require(). Attempting to use require() will cause a runtime error.
fix
Use ESM imports: import { ... } from 'react-realtime-hooks'. In Node.js, set "type": "module" in package.json or use dynamic import.
affects: >=2.0.0
deprecatedThe useReconnect hook is deprecated in v2.0.0. The reconnect functionality is now integrated into useWebSocket and useEventSource via the 'reconnect' option.
fix
Remove standalone useReconnect calls and configure reconnect within the transport hook options.
affects: >=2.0.0
gotchaStrict Mode safety: In React 18+ Strict Mode (double-rendering in development), the hook may open two WebSocket connections momentarily. The library handles cleanup, but ensure you do not rely on side effects in onOpen that assume a single connection.
fix
Avoid setting global state in onOpen that expects one-time initialization. Use useEffect for such side effects with appropriate dependencies.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'useState')
Missing React peer dependency or wrong version. The library requires React >=18.0.0.
fix
Install React 18 or 19: npm install react@18 react-dom@18
SyntaxError: Unexpected token 'export'
Package is ESM-only (v2+) and cannot be used with CommonJS require().
fix
Use ESM import syntax: import { useWebSocket } from 'react-realtime-hooks'; Or set "type": "module" in your package.json.
The 'heartbeat' option is not supported in this version.
Heartbeat was introduced in v2.0.0 and is not available in v1.x.
fix
Upgrade to v2.0.0 or later: npm install react-realtime-hooks@latest
Warning: useWebSocket received a 'url' that is not a string or URL object.
The 'url' prop is required and must be a string or URL object. It was passed as undefined or a non-URL type.
fix
Ensure you pass a valid WebSocket URL string (e.g., 'wss://example.com/socket') to useWebSocket. Use process.env variables with a fallback.
Upgrade
Version history
2.0.2latest on npm
Audit
Dependencies
reactrequiredPeer dependency: must be >=18.0.0 <20.0.0. The hooks rely on React's useState, useEffect, useRef, and useCallback.
Agent activity
15 hits · last 30 days
node
14
OpenAI (training)
1
Resources
react-realtime-hooks — npm install react-realtime-hooks · libregistry