Skip to content

Instantly share code, notes, and snippets.

@thekbbohara
Last active December 21, 2024 18:23
Show Gist options
  • Select an option

  • Save thekbbohara/85f0cca1d070d77929dcc11e6611e7f1 to your computer and use it in GitHub Desktop.

Select an option

Save thekbbohara/85f0cca1d070d77929dcc11e6611e7f1 to your computer and use it in GitHub Desktop.
qvsp
"use client";
import { useEffect, useRef } from "react";
import { io, type Socket } from "socket.io-client";
export const useSocket = (): Socket => {
const socketRef = useRef<Socket>();
if (!socketRef.current) {
socketRef.current = io("ws://ws.thekbbohara.xyz");
}
useEffect(() => {
const socket = socketRef.current;
if (!socket.connected) {
socket.connect();
}
return () => {
socket.disconnect();
};
}, []);
return socketRef.current;
};
---
vs
---
"use client";
import { useEffect, useState } from "react";
import { io, type Socket } from "socket.io-client";
export const useSocket = (): Socket | null => {
const [socket, setSocket] = useState<Socket | null>(null);
useEffect(() => {
const s: Socket = io("ws://ws.thekbbohara.xyz");
setSocket(s);
return () => {
s.disconnect();
};
}, []);
return socket;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment