@subburavi/react-socketio-context
v0.1.0
Published
A compact, configurable React & React Native friendly Socket.IO context + manager with runtime listeners and hooks.
Maintainers
Readme
@subburavi/react-socketio-context
A compact, configurable React & React Native friendly Socket.IO context + manager with runtime listeners and hooks.
Author: R SUbrahmanyam
Features
- Manage multiple named Socket.IO connections
- Add/remove listeners at runtime from any page/component
- Built-in support for optional per-socket or global
encrypt/decryptfunctions - React Context + hooks:
SocketProvider,useSocketManager,useSocket,useEmit,useSocketListener,useOnSocket - Works with React and React Native (pass platform-specific device APIs from your app)
- Small dependency surface
Install
npm install socket.io-client eventemitter3
# then add this package as a local dependency or build & publishQuick start
Wrap your app:
import React from "react";
import { SocketProvider } from "@subburavi/react-socketio-context";
function App() {
return (
<SocketProvider>
{/* ... */}
</SocketProvider>
);
}Create sockets at runtime and listen anywhere:
import { useSocketManager, useSocketListener, useOnSocket } from "@subburavi/react-socketio-context";
function Setup() {
const { createSocket } = useSocketManager();
React.useEffect(() => {
createSocket({
id: "main",
url: "wss://your-server:3025",
options: { transports: ["websocket"] },
listeners: {
"initial": (d) => console.log("initial", d)
}
});
}, [createSocket]);
return null;
}
function Page() {
useSocketListener("main", "Notify", (data) => { console.log("Notify", data); }, []);
return <div>Page</div>;
}License
MIT
