Skip to content

Instantly share code, notes, and snippets.

@Withoutbytes
Created November 27, 2021 11:07
Show Gist options
  • Save Withoutbytes/a4965a5953068355fc5d37d4cfc43026 to your computer and use it in GitHub Desktop.
Save Withoutbytes/a4965a5953068355fc5d37d4cfc43026 to your computer and use it in GitHub Desktop.
Use socket.io-client for react / next.js with lastMessage system and emit with auto cleanup.
import { useEffect, useState } from "react";
import { io, ManagerOptions, Socket, SocketOptions } from "socket.io-client";
export const useSocketIO = (
uri?: string | Partial<ManagerOptions & SocketOptions>,
opts?: Partial<ManagerOptions & SocketOptions>
): [Socket] => {
const [activeSocket, setActiveSocket] = useState<Socket>(null);
useEffect(() => {
const socket = io(uri, opts);
const onConnect = () => {
setActiveSocket(socket);
};
const onDisconnect = () => {
setActiveSocket(null);
};
socket.on("connect", onConnect);
socket.on("disconnect", onDisconnect);
return () => {
socket.removeListener("disconnect", onDisconnect);
socket.removeListener("connect", onConnect);
socket.disconnect();
};
}, []);
return [activeSocket];
};
export function useEventIO<TypeData>(
socket: Socket,
eventName: string
): [TypeData, (...args: any[]) => void] {
const [lastEvent, setLastEvent] = useState<TypeData>(null);
const emit = (...args: any[]) => {
if (!socket) {
throw new Error("Socket is not defined");
}
socket.emit(eventName, ...args);
};
useEffect(() => {
if (!socket) return;
socket.on(eventName, setLastEvent);
return () => {
socket.removeListener(eventName, setLastEvent);
};
}, [socket]);
return [lastEvent, emit];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment