Skip to content

Instantly share code, notes, and snippets.

@cocodrino
Created October 17, 2022 14:47
Show Gist options
  • Save cocodrino/7c4b486e41f5079bfb2725ebf8cccd3e to your computer and use it in GitHub Desktop.
Save cocodrino/7c4b486e41f5079bfb2725ebf8cccd3e to your computer and use it in GitHub Desktop.
wesocket react
export const WebsocketContext = createContext(false, null, () => {});
// ready, value, send
// Make sure to put WebsocketProvider higher up in
// the component tree than any consumers.
export const WebsocketProvider = ({ children }) => {
const [isReady, setIsReady] = useState(false);
const [val, setVal] = useState(null);
const ws = useRef(null);
useEffect(() => {
const socket = new WebSocket("wss://echo.websocket.events/");
socket.onopen = () => setIsReady(true);
socket.onclose = () => setIsReady(false);
socket.onmessage = (event) => setVal(event.data);
ws.current = socket;
return () => {
socket.close();
};
}, []);
const ret = [isReady, val, ws.current?.send.bind(ws.current)];
return (
<WebsocketContext.Provider value={ret}>
{children}
</WebsocketContext.Provider>
);
};
And there’s our context! To use it, we just need to create a consumer.
// Very similar to the WsHook component above.
export const WsConsumer = () => {
const [ready, val, send] = useContext(WebsocketContext); // use it just like a hook
useEffect(() => {
if (ready) {
send("test message");
}
}, [ready, send]); // make sure to include send in dependency array
return (
<div>
Ready: {JSON.stringify(ready)}, Value: {val}
</div>
);
};
@cocodrino
Copy link
Author

@willybeans
Copy link

willybeans commented Feb 10, 2024

hey that link is dead, any chance it still exists somewhere else? thanks for posting this!

@musantro
Copy link

musantro commented Aug 5, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment