npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-native-websocket-service

v1.2.0

Published

A reusable React Native WebSocket service with reconnect, heartbeat, AppState handling, and hooks.

Readme

react-native-websocket-service

A reusable WebSocket service for React Native with:

  • Auto-reconnect (exponential backoff + jitter)
  • Heartbeat with acknowledgment timeout
  • Connection timeout handling
  • AppState awareness (configurable background disconnect)
  • Optional NetInfo network-restore reconnect
  • Outbound message queue
  • Event emitter API + callbacks
  • useWebSocket React hook
  • TypeScript support

Installation

npm install react-native-websocket-service

Peer dependencies:

  • react-native (required)
  • react (required for useWebSocket)
  • @react-native-community/netinfo (optional — enables reconnect when network returns)
npm install @react-native-community/netinfo

Quick start

import { WebSocketService } from 'react-native-websocket-service';

const ws = new WebSocketService(
  {
    url: 'wss://example.com/socket',
    debug: true,
    heartbeatIntervalMs: 15000,
    heartbeatTimeoutMs: 5000,
    maxRetries: 5,
  },
  {
    onConnected: () => console.log('connected'),
    onDisconnected: () => console.log('disconnected'),
    onMessage: (msg) => console.log('message', msg),
    onError: (err) => console.error(err),
    onReconnecting: (attempt, delayMs) =>
      console.log(`retry #${attempt} in ${delayMs}ms`),
  },
);

ws.send({ type: 'chat', text: 'Hello' });
ws.disconnect();
ws.forceReconnect();
ws.destroy();

Hook usage

import { useWebSocket } from 'react-native-websocket-service';

function ChatScreen() {
  const { isConnected, send, disconnect } = useWebSocket(
    { url: 'wss://example.com/chat', debug: __DEV__ },
    {
      onMessage: (msg) => console.log(msg),
    },
  );

  return null;
}

Event emitter

const off = ws.on('message', (msg) => console.log(msg));
off();
// or: ws.off('message', handler)

Config

| Field | Type | Default | Description | |---|---|---|---| | url | string | required | WebSocket URL | | maxRetries | number | 5 | Max reconnect attempts (Infinity for unlimited) | | initialBackoffMs | number | 1000 | Base reconnect delay | | maxBackoffMs | number | 30000 | Backoff cap | | jitter | boolean | true | Randomize reconnect delay | | connectionTimeoutMs | number | 10000 | Connect timeout | | heartbeatIntervalMs | number | 30000 | Heartbeat interval (0 disables) | | heartbeatTimeoutMs | number | 10000 | Reconnect if no inbound message after heartbeat (0 disables) | | heartbeatPayload | object \| string | { type: 'heartbeat' } | Heartbeat payload | | protocols | string \| string[] | — | WebSocket protocols | | headers | Record<string,string> | — | RN WebSocket headers | | autoConnect | boolean | true | Connect in constructor | | queueMessages | boolean | true | Queue sends while disconnected | | maxQueueSize | number | 50 | Drop oldest when full | | disconnectOnAppState | 'background' \| 'inactive' \| false | 'background' | When to tear down on AppState | | reconnectOnActive | boolean | true | Reconnect when app becomes active | | enableNetworkReconnect | boolean | true | Use NetInfo when available | | debug | boolean | false | Verbose logs |

Behavior notes

  • Reconnect: unexpected close/error schedules exponential backoff. Manual disconnect() / destroy() do not.
  • forceReconnect: tears down without scheduling backoff, then connects after 100ms (no double-schedule).
  • Heartbeat: sends payload on an interval; if no inbound message arrives within heartbeatTimeoutMs, force-reconnects.
  • AppState: by default only background disconnects (not iOS inactive / Control Center). Returning to active reconnects if needed and resets retry count.
  • NetInfo: optional; when online again, retries reset and connect() is called.

API

Methods

| Method | Description | |---|---| | connect() | Start / resume connection | | disconnect() | Close without auto-reconnect | | send(data) | Send JSON object, string, or ArrayBuffer | | forceReconnect() | Close and reconnect immediately | | destroy() | Tear down listeners and prevent further use | | on / off | Event subscription |

Getters

isConnected, url, readyState, queuedCount, retryAttempt

License

MIT