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

sockr-client

v1.2.0

Published

Client-side websocket messaging with react hooks

Readme

sockr-client

A WebSocket client SDK with React hooks for real-time messaging, authentication, presence tracking, and typing indicators. Built on Socket.IO and designed to work with sockr-server.

Installation

npm install sockr-client

Optional peer dependency: React 16.8+ is needed for the React hooks. The core SocketClient class works without React.

Quick Start

With React

import { SocketProvider, useSocket, useMessages, useSendMessage } from "sockr-client";

function App() {
  return (
    <SocketProvider
      config={{ url: "http://localhost:3000" }}
      token="my-auth-token"
    >
      <Chat />
    </SocketProvider>
  );
}

function Chat() {
  const { isConnected, isAuthenticated } = useSocket();
  const { messages } = useMessages();
  const { sendMessage, isSending } = useSendMessage();

  if (!isConnected) return <p>Connecting...</p>;
  if (!isAuthenticated) return <p>Authenticating...</p>;

  return (
    <div>
      {messages.map((msg) => (
        <p key={msg.id}>
          <strong>{msg.from}:</strong> {msg.content}
        </p>
      ))}
      <button
        disabled={isSending}
        onClick={() => sendMessage("recipient-id", "Hello!")}
      >
        Send
      </button>
    </div>
  );
}

Without React

import { SocketClient } from "sockr-client";

const client = new SocketClient({
  url: "http://localhost:3000",
  reconnection: true,
});

client.onStateChange((state) => {
  console.log("Connection state:", state);
});

client.on("authenticated", ({ userId }) => {
  console.log("Logged in as", userId);
  client.sendMessage("bob", "Hey Bob!");
});

client.on("message", ({ from, content }) => {
  console.log(`${from}: ${content}`);
});

client.connect();
client.authenticate("my-auth-token");

API

SocketClient

The core client class for managing WebSocket connections, authentication, and messaging.

Constructor

new SocketClient(config: ClientConfig)

ClientConfig options:

| Option | Type | Default | Description | | --- | --- | --- | --- | | url | string | (required) | Server URL | | autoConnect | boolean | true | Connect automatically on creation | | reconnection | boolean | true | Auto-reconnect on disconnect | | reconnectionAttempts | number | 5 | Max reconnection attempts | | reconnectionDelay | number | 1000 | Base delay between attempts (ms) | | timeout | number | 20000 | Connection timeout (ms) | | transports | string[] | ["websocket", "polling"] | Allowed transports |

Methods

| Method | Returns | Description | | --- | --- | --- | | connect() | void | Establish the WebSocket connection | | disconnect() | void | Close the connection | | authenticate(token) | void | Authenticate with the server | | sendMessage(to, content, metadata?) | void | Send a direct message | | startTyping(to) | void | Notify a user you are typing | | stopTyping(to) | void | Clear typing indicator | | getOnlineStatus(userIds) | void | Request online status for users | | isConnected() | boolean | Check if connected | | isAuthenticated() | boolean | Check if authenticated | | getConnectionState() | ConnectionState | Get current connection state | | getUserId() | string \| null | Get the authenticated user ID | | on(event, handler) | () => void | Subscribe to events (returns cleanup) | | off(event, handler) | void | Unsubscribe from events | | onStateChange(listener) | () => void | Listen to state changes (returns cleanup) |

React Components & Hooks

<SocketProvider>

Provides socket context to your React tree.

<SocketProvider config={ClientConfig} token?: string>
  {children}
</SocketProvider>

| Prop | Type | Description | | --- | --- | --- | | config | ClientConfig | Connection configuration (required) | | token | string | Auth token (auto-authenticates when connected) |

useSocket()

Access the socket client and connection state.

const { client, isConnected, isAuthenticated, connectionState, userId } = useSocket();

useMessages()

Manage incoming messages.

const { messages, addMessage, clearMessages } = useMessages();

useSendMessage()

Send messages with loading and error states.

const { sendMessage, isSending, error } = useSendMessage();

usePresence()

Track which users are online.

const { onlineUsers, isUserOnline, checkOnlineStatus } = usePresence();

useTypingIndicator(timeout?)

Manage typing indicators with auto-timeout.

const { startTyping, stopTyping, usersTyping } = useTypingIndicator(3000);

useSocketEvent(event, handler, deps?)

Subscribe to any socket event within React lifecycle.

useSocketEvent("custom-event", (data) => {
  console.log(data);
}, []);

Connection States

enum ConnectionState {
  DISCONNECTED = "disconnected",
  CONNECTING = "connecting",
  CONNECTED = "connected",
  AUTHENTICATED = "authenticated",
  ERROR = "error",
  RECONNECTING = "reconnecting",
}

Connection Lifecycle

SocketClient created (autoConnect: true)
  -> State: CONNECTING
  -> WebSocket established
  -> State: CONNECTED
  -> Client calls authenticate(token)
  -> Server validates token
  -> State: AUTHENTICATED
  -> Client can send/receive messages
  -> Connection lost
  -> State: RECONNECTING (exponential backoff)
  -> Reconnected -> State: CONNECTED
  -> Client disconnects
  -> State: DISCONNECTED

Scripts

npm run dev     # Watch mode
npm run build   # Production build
npm run clean   # Remove dist/

Documentation

See Documentation.md for the full API reference.

License

MIT