βοΈWebsocket
Overview
How to use
Step 1: Install Dependencies
yarn add socket.io-clientStep 2: Create a WebSocket Hook
// useWebSocket.ts
import { useEffect, useRef } from 'react';
import { io, Socket } from 'socket.io-client';
type WebSocketEvent = 'connect' | 'disconnect' | 'message';
type WebSocketHook = {
socket: Socket | null;
connected: boolean;
connect: () => void;
disconnect: () => void;
sendMessage: (message: string) => void;
};
const useWebSocket = (): WebSocketHook => {
const socketRef = useRef<Socket | null>(null);
const connected = useRef(false);
useEffect(() => {
const socket = io(); // Initialize Socket.IO
socketRef.current = socket;
socket.on('connect', () => {
connected.current = true;
});
socket.on('disconnect', () => {
connected.current = false;
});
return () => {
socket.disconnect();
socketRef.current = null;
connected.current = false;
};
}, []);
const connect = () => {
if (socketRef.current && !connected.current) {
socketRef.current.connect();
}
};
const disconnect = () => {
if (socketRef.current && connected.current) {
socketRef.current.disconnect();
}
};
const sendMessage = (message: string) => {
if (socketRef.current && connected.current) {
socketRef.current.emit('message', message);
}
};
return {
socket: socketRef.current,
connected: connected.current,
connect,
disconnect,
sendMessage,
};
};
export default useWebSocket;Step 3: Use the WebSocket Hook in your Component
Last updated