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

react-simple-socket.io

v1.1.0

Published

A React context for setting up and using Socket.IO in your app

Downloads

12

Readme

React Simple Socket.IO

Easily use Socket.IO in your React app.

Ugh, another Socket.IO provider 🙄?

Seriously, how is this different from using plain Socket.IO?

  • Use a single instance of Socket.IO across all pages in your React app
  • Access the Socket.IO interface using a simple React Context API
  • Easily subscribe to socket events and use the return SocketEventSubscription object to easily unsubscribe
  • Easily setup global socket event handlers

Installation

React Simple Socket.IO marks React as a peer dependency. So you will need React installed in your app as well.

yarn add react react-simple-socket.io
npm install --save react react-simple-socket.io

Setup

In your index.tsx, wrap you app in the SocketProvider component

import React from "react";
import ReactDOM from "react-dom/client";
import { SocketProvider } from "react-simple-socket.io";
import App from "./app";

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <SocketProvider
    socketIoConfig={{
      uri: "<Socket URL Here>",
      options: {
        autoConnect: false
        /* Additional Socket.IO options */
      },
      // Optional globalEventHandlers map
      globalEventHandlers: {
        connect: () => {
        },
        "some-global-event": () => {
          /* Do something globally */
        }
      }
    }}>
    <App />
  </SocketProvider>
);

Global event handlers are automatically unsubscribed from when the SocketProvider unmounts

Usage

Now that you have the SocketProvider setup, you can use the context functions in your app.

chat-page.tsx

import React, { useEffect } from "react";
import {
  ChatMessage,
  ChatPanel,
  ChatUser,
  ChatMessageList,
  ChatInput
} from "ficticious-chat-library";
import { useSocketContext } from "react-simple-socket.io";
/* Other imports */

const ChatWidget = (): JSX.Element => {
  const { connect, disconnect, subscribe, emit } = useSocketContext();
  const [messages, setMessages] = useState<ChatMessage>([]);
  const [userTyping, setUserTyping] = useState<ChatUser>();

  const sendMessage = (text: string) => {
    emit("new-message", { msg: text });
  };

  useEffect(() => {
    // Subscribe to socket events when component mounts
    const onNewMessage = subscribe("new-message", data => {
      setMessages(list => [...list, new ChatMessage(data)]);
    });

    const onRemoteUserTyping = subscribe("start-typing", data => {
      setUserTyping(new ChatUser(data));
    });

    const onRemoteUserStopTyping = subscribe("stop-typing", data => {
      setUserTyping(undefined);
    });

    // Connect if Socket.IO autoConnect = false, manually connect
    connect();

    return () => {
      // Unsubscribe from socket events during unmount
      onNewMessage.unsubscribe();
      onRemoteUserTyping.unsubscribe();
      onRemoteUserStopTyping.unsubscribe();

      // Disconnect on unmount
      disconnect();
    };
  }, []);

  return (
    <ChatPanel>
      <ChatMessageList messages={messages} />

      {chatUser && <p>{chatUser.name} is typing</p>}

      <ChatInput onSend={sendMessage} />
    </ChatPanel>
  );
};

export default ChatWidget;

Running The Examples

The example/ folder contains:

  1. A simple Express server setup with Socket.IO
  2. An example client app demonstrating react-simple-socket.io;

To run the examples, first clone the project repository from GitHub:

git clone [email protected]:kwameopareasiedu/react-socket.io.git

Server Setup

  1. cd into example/server/
  2. Run yarn or npm install to install dependencies
  3. Run yarn start or npm start to start the server on port 3000

Client Setup

  1. cd into example/client/
  2. Run yarn or npm install to install dependencies
  3. Run yarn dev or npm start to start the client on port 3001
  4. Open your browser to http://localhost:3001 to access the client app

Open your browser devtools and navigate to the network tab to see the socket calls as you use the client app

Maintainers