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

Overview

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

You might also like...
⚡️ realtime scalable server performance monitor application built using react, node, redis and socket.io with clusters module.
⚡️ realtime scalable server performance monitor application built using react, node, redis and socket.io with clusters module.

PERFMonitor - Performance Monitoring System Introduction PERFMonitor is a web application that shows you performance and problems of one or more serve

Discord-clone - Discord Clone using React, ReactQuery, Tailwindcss, Redux, Socket IO, NodeJS, Express, MongoDB and Redis
Discord-clone - Discord Clone using React, ReactQuery, Tailwindcss, Redux, Socket IO, NodeJS, Express, MongoDB and Redis

Discord Clone using React, ReactQuery, Tailwindcss, Redux, Socket IO, NodeJS, Ex

CoderHouse - A Clubhouse project using Node, Express, Mongo, webRTC, socket.io, and React JS

codershouse-mern - This Project is Under Development. Below are some of the impl

Chat Application Using React, Node.js and Socket.io with MongoDB

Steps to Start the App Install the Public Dependencies Install the Server Dependencies In the Server Directory there's a .env file. Change the value o

Chat rooms using react and socket.io
Chat rooms using react and socket.io

Chat rooms This is a project I made to try out socket.io Both react and socket.io (at the time of writing) are relatively new to me. Running Locally R

A real-time chat application made using ReactJs, ExpressJs, NodeJs, and Socket.io.
A real-time chat application made using ReactJs, ExpressJs, NodeJs, and Socket.io.

insta-chat Live Site ScreenShots Instachat is a real-time chat app made with ReactJs on the front-end and ExpressJs , NodeJS , Socket.io web socket li

Instagram MERN - Full-Stack Instgram Clone using MERN Stack and Socket.io
Instagram MERN - Full-Stack Instgram Clone using MERN Stack and Socket.io

Instagram MERN Full-Stack Instgram Clone using MERN Stack and Socket.io Visit Now 🚀 🖥️ Tech Stack Frontend: Backend: Realtime Communication: Cloud S

💘 Dating app - Built with Node, React, Postgres, Socket.io & Material-UI
💘 Dating app - Built with Node, React, Postgres, Socket.io & Material-UI

Built with Node, React, Postgres, Socket.io & Material-UI The project Matcha is a dating app with the following features: 🌈 non-binary

IOT project using Spring Boot + ReactJS + Esp32 Socket implementation

iot-project Spring Boot - ReactJS - Esp32 Socket IOT Project Here is my IoT project using Spring Boot Stomp Socket - ReactJs - esp32 (and Arduino). Yo

Releases(1.1.0)
Owner
Kwame Opare Asiedu
Kwame Opare Asiedu
Web frontend of the NLW heat 2021 project, used: React; Typescript/TSX; Vite; Socket.io; Scss/Sass; and other libs for react (axios, context...).

This is the web frontend of the NLW heat 2021 project, carried out by rocketseat. It is free to use, and any questions or errors, please do not hesitate to consult me, or post an issue. In this code we used: React; Typescript/TSX; Vite; Socket.io; Scss/Sass; and other libs for react (axios, context...).

Guilherme Iuri 1 Oct 25, 2021
Example of chat web application using Socket.IO with the MERN stack Client in React

Real time chat app Example of chat web application using Socket.IO with the MERN

Lucifer1123 1 Dec 22, 2021
Pulse Share is a spinal cord stimulation setting community forum primarily for individuals living with SCI, clinicians, and researchers to characterize, share, observe, rate, and comment on spinal cord stimulation settings.

Pulse Share is a spinal cord stimulation setting community forum primarily for individuals living with SCI, clinicians, and researchers to characterize, share, observe, rate, and comment on spinal cord stimulation settings.

null 1 Jun 2, 2022
A Collabration Web-App using Express, React and Socket.io where Mutiple People can Join a Private room and Chat, Draw Among themselves. This project was selected as one of the best project at Tinkerhub Hacknight

A Collabration Web-App using Express, React and Socket.io where Mutiple People can Join a Private room and Chat, Draw Among themselves. This project was selected as one of the best project at Tinkerhub Hacknight

NzM 13 Dec 15, 2022
Video chat app built using React, Socket.io and WebRTC

Video Chat Web App It has been built using React, Material UI, Socket.io and WebRTC To open this on your browser click here Backend has been deployed

Thejas N U 4 Sep 23, 2022
Real-time chat app using Firebase, React, TailwindCSS, MongoDB, Node/Express, and Socket.io

Let's Chat A real-time chat application. Another fun side project :) GIFs are attached at the end. Technologies Used React and TailwindCSS for the fro

Hana Belay 31 Jan 4, 2023
Messanger - An messaging app buil on React and Redux with socket.io for real time chatting

An messaging app build on React and Redux with socket.io for real time chatting as MERN project you can make a gruop chat as well Login and sigup authenicate with bcrypt and json web token and complete chat is saved on Mongodb

Yash Raj 36 Dec 27, 2022
Realtime Chat App with React, Node.js, Socket.io and MongoDB

reactchatapp Realtime Chat App Features/Components Uses React Js for UI Backend using NodeJs Authentication using JWT MongoDB for database Socket.io f

Aayush Jha 15 Dec 22, 2022
Tinde-Chater is a Full Stack Chatting App. Uses Socket.io for real time communication and stores user details in encrypted format in Mongo DB Database.

Tinde-Chater is a Full Stack Chatting App. Uses Socket.io for real time communication and stores user details in encrypted format in Mongo DB Database.

Nitish Kumar 3 Jul 26, 2022
Discord Clone using React, Node, Express, Socket-IO and Mysql

React Discord Clone Functional Discord Clone written in Typescript using React, Socket IO, NodeJS, Express and MySQL View the live verison at -> http:

Eric Ellbogen 401 Dec 27, 2022