# React useWebSocket v2
[Live Demo](https://robtaussig.com/socket/)
Note: `wss://demos.kaazing.com/echo` has been down lately, so the demo will fail to connect when using that as the endpoint. On the plus side, this demonstrates the behavior of a connection failure.
[Test in StackBlitz](https://stackblitz.com/edit/react-huzf9f)
React Hook designed to provide robust WebSocket integrations to your React Components. Experimental support for SocketIO (read documentation below for more information)
Pull requests welcomed!
## New in v2
- `useWebSocket` now returns an object instead of an array. This allows you to pick out specific features/properties to suit your use-case as well as removing mental overhead of keeping track of item order.
- `lastJsonMessage` and `sendJsonMessage` added to return value to reduce need to stringify and parse outgoing and incoming messages at the component level.
- The optional object passed as the second parameter no longer needs to be static.
- Components can close/unsubscribe from a WebSocket by passing `false` as the third parameter. This provides a more explicit solution than the previous method of setting the `socketUrl` to `null`. Both methods work and are supported usage.
## Example Implementation
```js
import React, { useState, useCallback, useMemo, useRef } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const WebSocketDemo = () => {
//Public API that will echo messages sent to it back to the client
const [socketUrl, setSocketUrl] = useState('wss://echo.websocket.org');
const messageHistory = useRef([]);
const {
sendMessage,
lastMessage,
readyState,
} = useWebSocket(socketUrl);
messageHistory.current = useMemo(() =>
messageHistory.current.concat(lastMessage),[lastMessage]);
const handleClickChangeSocketUrl = useCallback(() =>
setSocketUrl('wss://demos.kaazing.com/echo'), []);
const handleClickSendMessage = useCallback(() =>
sendMessage('Hello'), []);
const connectionStatus = {
[ReadyState.CONNECTING]: 'Connecting',
[ReadyState.OPEN]: 'Open',
[ReadyState.CLOSING]: 'Closing',
[ReadyState.CLOSED]: 'Closed',
[ReadyState.UNINSTANTIATED]: 'Uninstantiated',
}[readyState];
return (
<div>
<button
onClick={handleClickChangeSocketUrl}
>
Click Me to change Socket Url
</button>
<button
onClick={handleClickSendMessage}
disabled={readyState !== ReadyState.OPEN}
>
Click Me to send 'Hello'
</button>
<span>The WebSocket is currently {connectionStatus}</span>
{lastMessage ? <span>Last message: {lastMessage.data}</span> : null}
<ul>
{messageHistory.current
.map((message, idx) => <span key={idx}>{message ? message.data : null}</span>)}
</ul>
</div>
);
};
```
From the example above, the component will rerender every time the `readyState` of the WebSocket changes, as well as when the WebSocket receives a message (which will change `lastMessage`). `sendMessage` is a memoized callback that will pass the message to the current WebSocket (referenced to internally with `useRef`).
A demo of this can be found [here](https://robtaussig.com/socket/). Each component uses its own `useWebSocket` hook. This implementation takes advantage of passing an optional options object (documented below). Among setting event callbacks (for `onmessage`, `onclose`, `onerror`, and `onopen`) that will log to the console, it is using the `share` option -- if multiple components pass the same socketUrl to `useWebSocket` and with `share` set to true, then only a single WebSocket will be created and `useWebSocket` will manage subscriptions/unsubscriptions internally. `useWebSocket` will keep track of how many subscribers any given WebSocket has and will automatically free it from memory once there are no subscribers remaining (a subscriber unsubscribes when it either unmounts or changes its socketUrl). Of course, multiple WebSockets can be created with the same target url, and so components are not required to share the same communication pipeline.
## Features
- Handles reconnect logic
- Multiple components can (optionally) use a single WebSocket, which is closed and cleaned up when all subscribed components have unsubscribed/unmounted
- Written in TypeScript
- Socket.io support
- No more waiting for the WebSocket to open before messages can be sent. Pre-connection messages are queued up and sent on connection
- Provides direct access to unshared WebSockets, while proxying shared WebSockets. Proxied WebSockets provide subscribers controlled access to the underlying (shared) WebSocket, without allowing unsafe behavior
- Seamlessly works with server-sent-events and the [EventSource API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)
## Getting Started
```sh
npm install react-use-websocket
```
```js
import useWebSocket from 'react-use-websocket';
// In functional React component
// This can also be an async getter function. See notes below on Async Urls.
const socketUrl = 'wss://echo.websocket.org';
const {
sendMessage,
sendJsonMessage,
lastMessage,
lastJsonMessage,
readyState,
getWebSocket
} = useWebSocket(socketUrl, {
onOpen: () => console.log('opened'),
//Will attempt to reconnect on all close events, such as server shutting down
shouldReconnect: (closeEvent) => true,
});
```
## Interface
```ts
type UseWebSocket = (
//Url can be return value of a memoized async function.
url: string | () => Promise<string>,
options: {
fromSocketIO?: boolean;
queryParams?: { [field: string]: any };
protocols?: string | string[];
share?: boolean;
onOpen?: (event: WebSocketEventMap['open']) => void;
onClose?: (event: WebSocketEventMap['close']) => void;
onMessage?: (event: WebSocketEventMap['message']) => void;
onError?: (event: WebSocketEventMap['error']) => void;
onReconnectStop?: (numAttempts: number) => void;
shouldReconnect?: (event: WebSocketEventMap['close']) => boolean;
reconnectInterval?: number;
reconnectAttempts?: number;
filter?: (message: WebSocketEventMap['message']) => boolean;
retryOnError?: boolean;
eventSourceOptions?: EventSourceInit;
} = {},
shouldConnect: boolean = true,
): {
sendMessage: (message: string) => void,
//jsonMessage must be JSON-parsable
sendJsonMessage: (jsonMessage: any) => void,
//null before first received message
lastMessage: WebSocketEventMap['message'] | null,
//null before first received message. If message.data is not JSON parsable, then this will be a static empty object
lastJsonMessage: WebSocketEventMap['message']['data'] | null,
// -1 if uninstantiated, otherwise follows WebSocket readyState mapping: 0: 'Connecting', 1 'OPEN', 2: 'CLOSING', 3: 'CLOSED'
readyState: number,
// If using a shared websocket, return value will be a proxy-wrapped websocket, with certain properties/methods protected
getWebSocket: () => (WebSocket | null),
}
```
## Requirements
- React 16.8+
- Cannot be used within a class component (must be a functional component that supports React Hooks)
## Async Urls
Instead of passing a string as the first argument to useWebSocket, you can pass a function that returns a string (or a promise that resolves to a string). It's important to note, however, that other rules still apply -- namely, that if the function reference changes, then it will be called again, potentially instantiating a new WebSocket if the returned url changes.
```js
import useWebSocket from 'react-use-websocket';
// In functional React component
const getSocketUrl = useCallback(() => {
return new Promise(resolve => {
setTimeout(() => {
resolve('wss://echo.websocket.org');
}, 2000);
});
}, []);
const {
sendMessage,
lastMessage,
readyState,
getWebSocket
} = useWebSocket(getSocketUrl, STATIC_OPTIONS);
```
## API
### sendMessage
```ts
type sendMessage = (messa

一行一诚
- 粉丝: 36
最新资源
- 基于Python和Django框架的现代化任务管理工具_任务追踪_待办事项管理_团队协作_优先级排序_截止日期提醒_项目进度可视化_用户权限控制_数据导出功能_多平台同步_旨在帮助.zip
- 基于卡尔曼滤波的机动目标跟踪算法在Matlab中的仿真实现_卡尔曼滤波机动目标跟踪算法仿真Matlab脚本文件运行说明_供机动目标跟踪算法的研究者进行参考和学习使用_Matlab2.zip
- 基于遗传算法与仿真模拟的列车时刻表优化研究项目_数学建模竞赛参赛论文工程文件_遗传算法优化_仿真模拟技术_列车调度问题_LaTeX排版_Git版本控制_数学建模方法_时间表优化算法.zip
- 基于Qt6_5_3和CMake构建的跨平台网格地图编辑器_支持网格创建_障碍物随机生成_路径规划算法可视化_代码编辑与高亮_JSON地图文件导入导出_实时图形界面交互_多图标资源管.zip
- 基于SpringBoot和Docker的在线编程评测与教学管理系统_支持Verilog和汇编语言题目自动评测GitLab集成教师出题与学生答题功能实时波形反馈与成绩统计_用于.zip
- 基于遗传算法与仿真优化技术的体检顾客顺序调度系统_遗传算法_局部搜索_单种群遗传算法_多种群遗传算法_仿真优化_序优化_最优计算量分配_OCBA_体检顾客调度_预约管理_排队优化_.zip
- 基于遗传算法进行乳腺肿瘤轮廓提取的电磁仿真优化研究_二维乳腺肿瘤模型构建_遗传算法优化轮廓搜索_共焦成像缩小轮廓范围_小区域遍历定位最佳轮廓位置_多线程FDTD文件运行_网格修改与.zip
- 基于A星与动态窗口法融合的电气设备巡检机器人路径规划算法研究_改进启发式函数与转向惩罚优化A星算法结合运动学模型与轨迹预测增强DWA算法通过固定采样分辨率策略实现全局路径优化与动态.zip
- 基于深度确定性策略梯度算法的IEEE30节点电力系统仿真训练集维护项目_电力系统仿真与强化学习训练环境构建_用于实现发电机出力优化电压控制负载均衡和系统损耗最小化的智能电网管理.zip
- HuangNO1_MY_OS_EXPRIENCE_18088_1756522410186.zip
- YJ-Eden_Trapezia_Algorithm_matlab_simulink_36836_1756522417259.zip
- UIDynamicBehaviorDemo项目极简说明_简化物理仿真行为的算法实现_通过简单的代码实现重力碰撞吸附等物理效果_内容关键词_物理仿真行为简化算法_重力效果模拟_碰撞检.zip
- 哈尔滨工业大学深圳校区2025年春季学期系统辨识课程个人实验算法仿真项目_系统辨识算法仿真与性能分析_用于教学演示和学生实验验证_MatlabSimulink系统建模参数估计最小二.zip
- 基于Java_Socket的Swirlds_Hashgraph_v2分布式共识算法仿真实现_改进共识流程与分片技术提升节点承载容量_用于构建高吞吐低延迟的分布式网络系统_Java_.zip
- 基于ClaraUE4和kyxz虚拟环境的空地协同智能无人系统仿真项目源码_北京理工大学未来精工技术2022级智能无人系统总体技术课程结课任务空地协同仿真_引入两无人车和两无人机实现.zip
- 路径规划与跟踪算法仿真测试框架_包含Dijkstra_AStar_RRT遗传算法路径规划器与PID_LQR_MPC控制器_动态可视化与性能对比分析_用于机器人自动驾驶无人机等智能系.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈


