perf: use websocket context

This commit is contained in:
hamster1963
2024-11-24 11:32:42 +08:00
parent 56d6305096
commit 5364d5cdb5
7 changed files with 81 additions and 34 deletions

View File

@@ -0,0 +1,11 @@
import { createContext } from "react";
export interface WebSocketContextType {
sendMessage: (message: string) => void;
lastMessage: MessageEvent | null;
readyState: number;
}
export const WebSocketContext = createContext<WebSocketContextType | undefined>(
undefined,
);

View File

@@ -0,0 +1,34 @@
import React from "react";
import {
WebSocketContext,
type WebSocketContextType,
} from "./websocket-context";
import useWebSocket from "react-use-websocket";
interface WebSocketProviderProps {
url: string;
children: React.ReactNode;
}
export const WebSocketProvider: React.FC<WebSocketProviderProps> = ({
url,
children,
}) => {
const { sendMessage, lastMessage, readyState } = useWebSocket(url, {
reconnectAttempts: 10,
reconnectInterval: 3000,
shouldReconnect: () => true,
});
const contextValue: WebSocketContextType = {
sendMessage,
lastMessage,
readyState,
};
return (
<WebSocketContext.Provider value={contextValue}>
{children}
</WebSocketContext.Provider>
);
};