New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

react-native-websocket-service

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-websocket-service

A reusable WebSocket service with reconnect, heartbeat, and React Native support.

latest
npmnpm
Version
1.1.0
Version published
Maintainers
1
Created
Source

WebSocketService

A reusable WebSocket service for React Native with:

  • Auto-reconnect (with exponential backoff)
  • Heartbeat messages
  • Connection timeout handling
  • AppState awareness (pause/resume connections when app is backgrounded/foregrounded)
  • TypeScript support

This service is generic enough for real-time data updates, chat applications, and more.

Installation

Since this library depends on React Native’s AppState, it requires react-native in your project.

npm install websocket-service

In your package.json, react-native will be a peer dependency, so make sure it’s already installed in your project.

Usage 

import { WebSocketService } from '@yourname/websocket-service';

const ws = new WebSocketService(
  {
    url: 'wss://example.com/socket',
    heartbeatIntervalMs: 15000, // optional
    maxRetries: 5,              // optional
  },
  {
    onConnected: () => console.log("✅ Connected"),
    onDisconnected: () => console.log("❌ Disconnected"),
    onMessage: (msg) => console.log("💬 Received:", msg),
    onError: (err) => console.error("Error:", err),
  }
);

// Sending data
ws.send({ type: 'chat', text: 'Hello World!' });

// Manually disconnect
ws.disconnect();

// Force reconnect
ws.forceReconnect();

// Destroy completely (no reconnects)
ws.destroy();


API
Constructor

new WebSocketService(config: WebSocketConfig, callbacks?: WebSocketCallbacks)


WebSocketConfig
Field	Type	Default	Description
url	string	Required	The WebSocket server URL
maxRetries	number	5	Max reconnection attempts
initialBackoffMs	number	1000	Initial delay before reconnect (ms)
connectionTimeoutMs	number	10000	Time to wait for connection before timing out
heartbeatIntervalMs	number	30000	Interval to send heartbeat messages
WebSocketCallbacks
Callback	Parameters	Description
onConnected	()	Called when connection opens
onDisconnected	()	Called when connection closes
onMessage	(message: string)	Called when a message is received
onError	(error: Error)	Called on connection error
Methods
Method	Description
connect()	Manually initiate/retry a connection
disconnect()	Close connection without retry
send(data)	Send JSON data to server
forceReconnect()	Immediately close and reconnect
destroy()	Close connection and remove all listeners
isConnected (getter)	boolean – current connection state
url (getter)	string – current URL
readyState (getter)	WebSocket ready state number
Example: Sports Data Feed
const sportsSocket = new WebSocketService(
  { url: 'wss://sports.example.com/live' },
  {
    onMessage: (msg) => {
      const data = JSON.parse(msg);
      console.log("🏀 Live update:", data);
    }
  }
);

Example: Chat
const chatSocket = new WebSocketService(
  { url: 'wss://chat.example.com' },
  {
    onConnected: () => console.log("Chat connected"),
    onMessage: (msg) => console.log("Chat:", msg)
  }
);

chatSocket.send({ type: 'message', user: 'Abrham', text: 'Hi!' });

License

MIT


Keywords

websocket

FAQs

Package last updated on 14 Aug 2025

Did you know?

Socket

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.

Install

Related posts