react-websocket-hooks
v1.0.0
Published
Lightweight React hooks for managing WebSocket connections.
Maintainers
Readme
🔌 react-websocket-hooks
Lightweight React hooks to simplify WebSocket integration in functional components.
✨ Features
- 📡 Establish and manage WebSocket connections
- 🧼 Auto cleanup on component unmount
- 🔁 Easy message sending
- 💬 Real-time message listening
- 🧪 Unit tested with mocked WebSocket
📦 Installation
npm install react-websocket-hooksor
yarn add react-websocket-hooks⚙️ Usage
Basic Example
import React from "react";
import { useWebSocket } from "react-websocket-hooks";
const MyComponent = () => {
const { sendMessage } = useWebSocket("wss://echo.websocket.org");
const handleSend = () => {
sendMessage("Hello WebSocket");
};
return (
<div>
<button onClick={handleSend}>Send Message</button>
</div>
);
};
export default MyComponent;🧩 API
useWebSocket(url: string)
| Return value | Description |
| --------------- | ---------------------------------------- |
| sendMessage() | Function to send a message to the server |
| close() | Manually close the WebSocket connection |
| webSocket | Raw WebSocket instance (optional use) |
🧪 Testing
This package includes full test coverage for connection, messaging, and teardown behavior.
Run tests
npm run test📁 Project Structure
react-websocket-hooks/
├── src/
│ ├── useWebSocket.ts # Hook source
│ └── test/useWebSocket.test.ts # Unit tests with Jest
├── package.json
├── tsconfig.json
└── README.md📜 License
MIT © Yogaraj Saravanan
