react-io-client
v1.2.2
Published
A socket.io-client hook for react in Typescript.
Downloads
14
Maintainers
Readme
react-io-client
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.