Last active
October 28, 2020 10:27
-
-
Save tpjnorton/e3f82e512f2a6600b07d1ba659f3ae63 to your computer and use it in GitHub Desktop.
A Handy React Hook for creating auto-closing WebSockets.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const useWebSocket = (url, protocols, onMessage, onError) => { | |
const ws = useRef(null); | |
useEffect(() => { | |
const socket = new WebSocket(url, protocols); | |
socket.onmessage = onMessage; | |
socket.onerror = onError; | |
ws.current = socket; | |
return () => { | |
ws.current.close(); | |
}; | |
}, []); | |
return ws; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment