useWebsocket
React hook and provider to integrate WebSockets into your React Components.
Live Demo
Pull requests welcomed!
Installation
npm install --save use-awesome-websocket
or
yarn add use-awesome-websocket
Usage
WebSocketProvider
WebSocketProvider
is a React component that provides a WebSocket connection to your entire React application.
It wraps the child components with a context provider, allowing them to access the socket connection via the useWebSocket
hook.
It takes two props in the interface:
export interface WebSocketProviderProps {
disconnectOnUnmount?: boolean;
url?: string;
}
Here's an example of how to use it:
import { WebSocketProvider } from 'use-awesome-websocket';
function App() {
return (
<WebSocketProvider url="wss://your-websocket-url">
<YourComponent />
</WebSocketProvider>
);
}
Please replace wss://your-websocket-url
with your actual ws url.
Please replace <YourComponent />
with your actual component.
useWebsocket
useWebsocket
is a custom React hook that allows you to interact with the WebSocket connection provided by WebSocketProvider
.
You can provide the following properties:
export interface UseWebSocketProps<
ReturnedMessageType extends WebSocketJSONType,
> extends WebSocketEvents<ReturnedMessageType> {
disconnectOnUnmount?: boolean;
endpoint?: string;
maxRetries?: number;
reconnectInterval?: number;
shouldConnect?: boolean;
shouldReconnectOnClose?: (closeEvent: WebSocketEventMap['close']) => boolean;
shouldRetryOnError?: boolean;
url?: string;
}
And the hook returns the following interface:
export interface UseWebSocketReturn<
ReturnedMessageType extends WebSocketJSONType,
SendMessageType extends WebSocketJSONType,
> extends WebSocketState<ReturnedMessageType> {
connect: () => WebSocket;
sendData: (
data: SendMessageType,
options?: { shouldQueue?: boolean; shouldResendOnReconnect?: boolean }
) => void;
websocket: WebSocket;
}
Here's an example of how to use it:
import { useWebsocket } from 'use-awesome-websocket';
function YourComponent() {
const { readyState, sendData, lastData } = useWebSocket<string, string>({
url: 'wss://your-websocket-url',
});
const [messageHistory, setMessageHistory] = useState<string[]>([]);
useEffect(() => {
if (lastData) {
setMessageHistory((prev) => [...prev, lastData]);
}
}, [lastData]);
useEffect(() => {
sendData('First Message on effect!', {
shouldQueue: true,
shouldResendOnReconnect: true,
});
}, []);
return (
<div>
<button
type="button"
onClick={() =>
sendData('Hello', {
shouldResendOnReconnect: true,
})
}
disabled={readyState !== WEBSOCKET_READY_STATE.OPEN}
>
Click to send 'Hello'
</button>
<button
type="button"
onClick={() => sendData('Bye')}
disabled={readyState !== WEBSOCKET_READY_STATE.OPEN}
>
Click to send 'Bye'
</button>
<p>
The WebSocket ready state is:{' '}
<strong>{connectionMap[readyState]}</strong>
</p>
<h3>Last data </h3>
{lastData ? <p>Last message: {lastData}</p> : null}
<h3>Message history</h3>
<ul>
{messageHistory.map((message, index) => (
// eslint-disable-next-line react/no-array-index-key
<li key={index}>{message || null}</li>
))}
</ul>
</div>
);
}
Requirements
- React >=17
- Cannot be used within a class component (must be a functional component that supports React Hooks)