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 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-awesome-websocket

v1.0.5

Published

React hook and provider to integrate WebSockets into your React Components

Downloads

8

Readme

useWebsocket

React hook and provider to integrate WebSockets into your React Components.

Live Demo

Pull requests welcomed!

Installation

npm install --save use-awesome-websocket

or

yarn add use-awesome-websocket

Usage

WebSocketProvider

WebSocketProvider is a React component that provides a WebSocket connection to your entire React application. It wraps the child components with a context provider, allowing them to access the socket connection via the useWebSocket hook. It takes two props in the interface:

export interface WebSocketProviderProps {
  /**
   * If you want disconnect all sockets on unmount you can set it via the provider
   * @default true
   */
  disconnectOnUnmount?: boolean;
  /**
   * If you want to set a default url for the websocket connection you can set it via the provider
   */
  url?: string;
}

Here's an example of how to use it:

import { WebSocketProvider } from 'use-awesome-websocket';

function App() {
  return (
    <WebSocketProvider url="wss://your-websocket-url">
      <YourComponent />
    </WebSocketProvider>
  );
}

Please replace wss://your-websocket-url with your actual ws url. Please replace <YourComponent /> with your actual component.

useWebsocket

useWebsocket is a custom React hook that allows you to interact with the WebSocket connection provided by WebSocketProvider. You can provide the following properties:

export interface UseWebSocketProps<
  ReturnedMessageType extends WebSocketJSONType,
> extends WebSocketEvents<ReturnedMessageType> {
  /**
   * Disconnect the websocket connection on unmount
   * @default true
   */
  disconnectOnUnmount?: boolean;
  /**
   * The endpoint to connect to, comes after the url. eg: wss://example.com/endpoint
   */
  endpoint?: string;
  /**
   * Maximum number of retries to connect
   * @default 5
   */
  maxRetries?: number;
  /**
   * Interval to reconnect in milliseconds
   * @default 1000
   */
  reconnectInterval?: number;
  /**
   * Determine if it should connect to the websocket server on mount
   * @default true
   */
  shouldConnect?: boolean;
  /**
   * Determine if it should reconnect on close events, such as server shutting down
   * @default () => true
   */
  shouldReconnectOnClose?: (closeEvent: WebSocketEventMap['close']) => boolean;
  /**
   * Retry connecting on error
   * @default false
   */
  shouldRetryOnError?: boolean;
  /**
   * URL to connect to
   */
  url?: string;
}

And the hook returns the following interface:

export interface UseWebSocketReturn<
  ReturnedMessageType extends WebSocketJSONType,
  SendMessageType extends WebSocketJSONType,
> extends WebSocketState<ReturnedMessageType> {
  connect: () => WebSocket;
  /**
   * Send data to the websocket server:
   * - If the connection is open, send the data directly
   * - If the connection is not open yet, add the data to the messages queue when shouldQueue is true and send the data when the connection is opened.
   * - If the connection is closed, resend the data when the connection is reopened when shouldResendOnReconnect is true
   */
  sendData: (
    data: SendMessageType,
    options?: { shouldQueue?: boolean; shouldResendOnReconnect?: boolean }
  ) => void;

  websocket: WebSocket;
}

Here's an example of how to use it:

import { useWebsocket, WEBSOCKET_READY_STATE } from 'use-awesome-websocket';


const connectionMap = {
  [WEBSOCKET_READY_STATE.CONNECTING]: 'Connecting',
  [WEBSOCKET_READY_STATE.OPEN]: 'Open',
  [WEBSOCKET_READY_STATE.CLOSING]: 'Closing',
  [WEBSOCKET_READY_STATE.CLOSED]: 'Closed',
  [WEBSOCKET_READY_STATE.UNINSTANTIATED]: 'Uninstantiated',
};

function YourComponent() {
  const { readyState, sendData, lastData } = useWebSocket<string, string>({
    url: 'wss://your-websocket-url',
  });
  const [messageHistory, setMessageHistory] = useState<string[]>([]);

  useEffect(() => {
    if (lastData) {
      setMessageHistory((prev) => [...prev, lastData]);
    }
  }, [lastData]);

  useEffect(() => {
    sendData('First Message on effect!', {
      shouldQueue: true,
      shouldResendOnReconnect: true,
    });
  }, []);

  return (
    <div>
      <button
        type="button"
        onClick={() =>
          sendData('Hello', {
            shouldResendOnReconnect: true,
          })
        }
        disabled={readyState !== WEBSOCKET_READY_STATE.OPEN}
      >
        Click to send &apos;Hello&apos;
      </button>
      <button
        type="button"
        onClick={() => sendData('Bye')}
        disabled={readyState !== WEBSOCKET_READY_STATE.OPEN}
      >
        Click to send &apos;Bye&apos;
      </button>
      <p>
        The WebSocket ready state is:{' '}
        <strong>{connectionMap[readyState]}</strong>
      </p>
      <h3>Last data </h3>
      {lastData ? <p>Last message: {lastData}</p> : null}
      <h3>Message history</h3>
      <ul>
        {messageHistory.map((message, index) => (
          // eslint-disable-next-line react/no-array-index-key
          <li key={index}>{message || null}</li>
        ))}
      </ul>
    </div>
  );
}

Requirements

  • React >=17
  • Cannot be used within a class component (must be a functional component that supports React Hooks)