Skip to content

Instantly share code, notes, and snippets.

@tpjnorton
Last active October 28, 2020 10:27
Show Gist options
  • Save tpjnorton/e3f82e512f2a6600b07d1ba659f3ae63 to your computer and use it in GitHub Desktop.
Save tpjnorton/e3f82e512f2a6600b07d1ba659f3ae63 to your computer and use it in GitHub Desktop.
A Handy React Hook for creating auto-closing WebSockets.
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