
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
react-ws-kit
Advanced tools
Production-quality typed WebSocket hook for React with intelligent connection sharing, auto-reconnect, and message queuing
A production-quality, typed WebSocket hook for React with intelligent connection sharing, message queuing, and comprehensive reconnection handling.
allData history and UI statenpm install react-ws-kit
import { useSocket } from 'react-ws-kit'
function ChatComponent() {
const { connect, disconnect, send, status, lastReturnedData, allData } =
useSocket('ws://localhost:3001/chat')
return (
<div>
<button onClick={connect}>Connect</button>
<button onClick={disconnect}>Disconnect</button>
<button onClick={() => send({ message: 'Hello!' })}>Send</button>
<p>Status: {status}</p>
</div>
)
}
type MessageIn = {
type: 'chat'
user: string
message: string
timestamp: number
}
type MessageOut = {
message: string
}
function TypedChat() {
const { send, lastReturnedData, allData } = useSocket<MessageIn, MessageOut>(
'ws://localhost:3001/chat',
{
autoConnect: true,
autoReconnect: true,
reconnectAttempts: 5,
reconnectDelay: 1000,
queueMessages: true,
maxQueueSize: 100
}
)
// lastReturnedData is typed as MessageIn | undefined
// send accepts MessageOut
return <div>{lastReturnedData?.message}</div>
}
useSocket<TIn, TOut>(url, options?)url: string - WebSocket URLoptions?: Options<TIn, TOut> - Configuration object| Option | Type | Default | Description |
|---|---|---|---|
autoConnect | boolean | false | Connect automatically on mount |
protocols | string | string[] | undefined | WebSocket sub-protocols |
autoReconnect | boolean | false | Enable automatic reconnection |
reconnectAttempts | number | Infinity | Max reconnection attempts |
reconnectDelay | number | 1000 | Base delay in ms (linear backoff) |
queueMessages | boolean | false | Queue messages when disconnected |
maxQueueSize | number | 50 | Maximum queue size |
parse | (event: MessageEvent) => TIn | JSON.parse | Custom message parser |
serialize | (data: TOut) => string | JSON.stringify | Custom message serializer |
key | string | undefined | Deterministic key for function identity |
heartbeat | HeartbeatOptions | undefined | Heartbeat/ping configuration (see below) |
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enable automatic heartbeat/ping |
interval | number | 30000 | Interval between ping messages (ms) |
timeout | number | 5000 | Timeout waiting for pong response (ms) |
pingMessage | TOut | (() => TOut) | { type: 'ping' } | Message to send as ping |
isPong | (message: TIn) => boolean | (msg) => msg?.type === 'pong' | Function to detect pong response |
reconnectOnFailure | boolean | true | Trigger reconnection on heartbeat failure |
{
connect: () => void
disconnect: () => void
send: (data: TOut) => void
status: "disconnected" | "connecting" | "connected" | "error" | "reconnecting"
lastReturnedData?: TIn
allData: TIn[]
killSocketForAllSubscribers: () => void
}
Hooks automatically share a WebSocket if all of the following match:
key option)// These two hooks share the same WebSocket
function ComponentA() {
const ws = useSocket('ws://localhost:3001/chat', { queueMessages: true })
// ...
}
function ComponentB() {
const ws = useSocket('ws://localhost:3001/chat', { queueMessages: true })
// ...
}
Linear backoff: delay = reconnectDelay * attemptNumber
useSocket(url, {
autoReconnect: true,
reconnectAttempts: 5,
reconnectDelay: 1000
})
// Attempt 1: 1000ms delay
// Attempt 2: 2000ms delay
// Attempt 3: 3000ms delay
// ...
The kill switch closes the socket for all subscribers and prevents auto-reconnect:
const { killSocketForAllSubscribers } = useSocket(url, { autoReconnect: true })
// Disconnects all components using this socket
// Auto-reconnect is disabled until manual connect()
killSocketForAllSubscribers()
When queueMessages: true, messages sent while disconnected are queued and flushed on reconnection:
const { send } = useSocket(url, {
queueMessages: true,
maxQueueSize: 100
})
// Even if disconnected, messages are queued
send({ message: 'Hello' })
send({ message: 'World' })
// On reconnect, both messages are sent in order
Enable automatic connection health monitoring with heartbeat/ping:
const socket = useSocket('ws://api.example.com/chat', {
autoConnect: true,
autoReconnect: true,
heartbeat: {
enabled: true,
interval: 30000, // Send ping every 30 seconds
timeout: 5000, // Expect pong within 5 seconds
pingMessage: { type: 'ping' },
isPong: (msg) => msg.type === 'pong',
reconnectOnFailure: true // Auto-reconnect if pong not received
}
})
You can customize the ping message format and pong detection:
const socket = useSocket('ws://api.example.com/chat', {
heartbeat: {
enabled: true,
interval: 20000,
// Dynamic ping message
pingMessage: () => ({
cmd: 'heartbeat',
timestamp: Date.now()
}),
// Custom pong detection
isPong: (msg) => msg.cmd === 'heartbeat_ack',
}
})
isPong() is received, the heartbeat timer is resetreconnectOnFailure is true, the socket will close and trigger auto-reconnectallData or lastReturnedDataIf your WebSocket server uses native WebSocket ping/pong frames (not application-level messages), you don't need to configure heartbeat - the browser handles it automatically!
The package includes comprehensive unit tests:
npm test
MIT
FAQs
Production-quality typed WebSocket hook for React with intelligent connection sharing, auto-reconnect, and message queuing
The npm package react-ws-kit receives a total of 0 weekly downloads. As such, react-ws-kit popularity was classified as not popular.
We found that react-ws-kit demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.