react-io-client
TypeScript icon, indicating that this package has built-in type declarations

1.2.2 • Public • Published

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.

Package Sidebar

Install

npm i react-io-client

Weekly Downloads

2

Version

1.2.2

License

MIT

Unpacked Size

5.06 kB

Total Files

6

Last publish

Collaborators

  • finneas28