MCPcopy
hub / github.com/alibaba/hooks / useWebSocket

Function useWebSocket

packages/hooks/src/useWebSocket/index.ts:34–168  ·  view source on GitHub ↗
(socketUrl: string, options: Options = {})

Source from the content-addressed store, hash-verified

32}
33
34function useWebSocket(socketUrl: string, options: Options = {}): Result {
35 const {
36 reconnectLimit = 3,
37 reconnectInterval = 3 * 1000,
38 manual = false,
39 onOpen,
40 onClose,
41 onMessage,
42 onError,
43 protocols,
44 } = options;
45
46 const [latestMessage, setLatestMessage] = useState<WebSocketEventMap['message']>();
47 const [readyState, setReadyState] = useState<ReadyState>(ReadyState.Closed);
48
49 const onOpenRef = useLatest(onOpen);
50 const onCloseRef = useLatest(onClose);
51 const onMessageRef = useLatest(onMessage);
52 const onErrorRef = useLatest(onError);
53 const readyStateRef = useLatest(readyState);
54
55 const reconnectTimesRef = useRef(0);
56 const reconnectTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
57
58 const websocketRef = useRef<WebSocket>(undefined);
59
60 const reconnect = () => {
61 if (
62 reconnectTimesRef.current < reconnectLimit &&
63 websocketRef.current?.readyState !== ReadyState.Open
64 ) {
65 if (reconnectTimerRef.current) {
66 clearTimeout(reconnectTimerRef.current);
67 }
68
69 reconnectTimerRef.current = setTimeout(() => {
70 // eslint-disable-next-line @typescript-eslint/no-use-before-define
71 connectWs();
72 reconnectTimesRef.current++;
73 }, reconnectInterval);
74 }
75 };
76
77 const connectWs = () => {
78 if (reconnectTimerRef.current) {
79 clearTimeout(reconnectTimerRef.current);
80 }
81
82 if (websocketRef.current) {
83 websocketRef.current.close();
84 }
85
86 const ws = new WebSocket(socketUrl, protocols);
87 setReadyState(ReadyState.Connecting);
88
89 ws.onerror = (event) => {
90 if (websocketRef.current !== ws) {
91 return;

Callers 2

demo1.tsxFile · 0.85
index.spec.tsFile · 0.85

Calls 5

useLatestFunction · 0.85
connectFunction · 0.85
useUnmountFunction · 0.85
disconnectFunction · 0.85
useMemoizedFnFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…