Skip to content

Instantly share code, notes, and snippets.

@mohsenasm
Last active April 15, 2020 06:56
Show Gist options
  • Save mohsenasm/5b01a8cc82e9140df8a86860bd16d108 to your computer and use it in GitHub Desktop.
Save mohsenasm/5b01a8cc82e9140df8a86860bd16d108 to your computer and use it in GitHub Desktop.
React WebSocket With Hook
import { useState, useCallback, useRef } from 'react';
function useWebSocket(url) {
const [isConnected, setConnected] = useState(false);
const [socket, setSocket] = useState(null);
const isReconnectionEnable = useRef(true);
const setReconnectionEnable = useCallback((newValue) => {
isReconnectionEnable.current = newValue;
}, []);
const reconnectInterval = useRef(5000);
const setReconnectInterval = useCallback((newValue) => {
reconnectInterval.current = newValue;
}, []);
const onOpen = useRef(() => { });
const onClose = useRef(() => { });
const onMessage = useRef(() => { });
const onError = useRef(() => { });
const setOnOpen = (f) => {
onOpen.current = f;
};
const setOnClose = (f) => {
onClose.current = f;
};
const setOnMessage = (f) => {
onMessage.current = f;
};
const setOnError = (f) => {
onError.current = f;
};
const reconnect = useCallback(() => {
const newSocket = new WebSocket(url);
newSocket.onopen = (event) => {
setConnected(true);
onOpen.current(event);
};
newSocket.onmessage = (event) => {
onMessage.current(event);
}
newSocket.onerror = (event) => {
onError.current(event);
setConnected(false);
}
newSocket.onclose = (event) => {
onClose.current(event);
setConnected(false);
if (isReconnectionEnable.current)
setTimeout(() => {
console.log("** web socket reconnecting onClose **");
reconnect();
}, reconnectInterval.current);
}
setSocket(newSocket);
}, [url]);
// use this code in parrent component to connect
// OR uncomment this to connect automatically
// useEffect(() => {
// reconnect()
// }, [reconnect]);
return {
socket, reconnect, isConnected,
setReconnectionEnable, setReconnectInterval,
setOnOpen, setOnMessage, setOnClose, setOnError
}
}
export default useWebSocket;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment