I'm working on this React app which uses websockets, first off, some background information:
I got a fooArray
which the user can change with a hook, I got a socket
which changes on mount. Now, I got the following code, the // foo array change listener
is the one which I'm talking about. I included the other ones for easier understanding
// socket ref
const socket = useRef(null);
// foo array change listener
useEffect(() => {
// this === null is there to prevent emitting on something that's null,
// if another way is possible too, please let me know.
if (socket.current === null) return;
socket.current.emit('foos', JSON.stringify(fooArray));
}, [fooArray, socket.current]);
// socket connection on mount
useEffect(() => {
socket.current = ioClient(WS_URI);
}, []);
Now the problem is, if I remove socket.current from the dependency array of the fooArray change listener
, the useEffect hook won't execute and the emit event won't occur when the websocket is connected.
How would I use this to make socket.current become a part of the dependency array and not be unused..?