Skip to content

Finneasles/react-io-client

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-io-client

thumbnail

Note: The socket connection does not come with any event handlers. Those should be added and managed by the component that use this hook. More information.

Getting Started

Install dependency:

npm i react-io-client

Example

Here's an example of how to use the useSocket hook in a React component:

import { useSocket } from  "react-io-client";
import  React, { useEffect, useState } from  "react";

export  default  function  Chat() {
const [socket] = useSocket("ws://localhost:3000", { autoConnect:  false });
const [messages, setMessages] = useState([]);

useEffect(() => {
if (!socket) return;
socket.on("message", (message: string) => {
setMessages((prevMessages) => [...prevMessages, message]);
});
socket.emit("join", "room1");
return () => {
socket.off("message");
socket.emit("leave", "room1");
};
}, [socket]);

return messages.map((message, index) => {
return <div  key={index}>{message}</div>;
});
}

Learn More

  • The hook must be wrapped in a useEffect to avoid memory leaks.

You can learn more in the Documentation.

About

A socket.io-client hook for react built with Typescript.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published