Using React Context with Socket.io (and react hooks!)

/components/socket_context/
--- context.js - creates and exports the Context
--- index.js - creates the Provider that will wrap the app.
import React, { createContext } from "react"; const SocketContext = createContext({  
queueLength: 0,
positionInLine: 0,
});
export default SocketContext;
import React, { useState, useEffect } from "react";
import SocketContext from "Components/socket_context/context";
import { initSockets } from "../../path/to/sockets";
// ^ initSockets is shown later on
const SocketProvider = (props) => {
const [value, setValue] = useState({
queueLength: 0,
positionInLine: 0,
});
useEffect(() => initSockets({ setValue }), [initSockets]);
// Note, we are passing setValue ^ to initSockets
return(
<SocketContext.Provider value={ value }>
{ props.children }
</SocketContext.Provider>
)
};
export default SocketProvider;
import React from "react";
import { render } from "react-dom";
import SocketProvider from "Components/socket_context";
import App from "Components/app";
const renderApp = App => {
render(
<SocketProvider>
<App/>
</SocketProvider>
document.getElementById("root")
);
}
renderApp(App);
/sockets
---index.js
---events.js
---emit.js
import io from "socket.io-client;
import { socketEvents } from "./events";
import { getQueueLength } from "./emit";
export const socket = io();
export const initSockets = ({ setValue }) => {
socketEvents({ setValue });
// setValue ^ is passed on to be used by socketEvents
getQueueLength();
};
import { socket } from './index';export const socketEvents = ({ setValue }) => {
socket.on('queueLength', ({ queueLength }) => {
setValue(state => { return { ...state, queueLength } });
});
socket.on('positionInLine', ({ positionInLine }) => {
setValue(state => { return { ...state, positionInLine } });
});
};
import { socket } from "./index";export const addClientToQueue = () => {
socket.emit('addClientIdToQueue');
};
export const getQueueLength = () => {
socket.emit('queueLengthToSocket');
};
export const removeUserFromQueue = () => {
socket.emit('removeUserFromQueue');
};
import React, { useContext } from "react";
import SocketContext from '../components/socket_context/context'
const Lobby = props => {
const { positionInLine, queueLength } = useContext(SocketContext);
return (
<div>
{ queueLength }
^ This will update every time the server emits queueLength
</div>
)
}
// DO NOT do this! 
<SocketContext.Provider value={{ some: 0, stuff: 0 }}>

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store