Skip to content Skip to sidebar Skip to footer

Where To Put Your Websocket In React

I have been trying to use socket.io with react for some time and I still don't know where to initiate socket = io(endpoint). In most tutorials I have seen, they seem to put it at t

Solution 1:

I encountered a problem like yours that I need to listen to some events consistently regardless of which route you navigate to in my app. I manage to do it by initialized the socket on the top level component outside rendering function and exported it, so when I need to emit or listen to a socket I will just import it.

/* socket initialization here */
socket = io(endpoint);

constApp = () => {
    //return <Routes>...</Routes>
}

exportdefaultApp;
export {socket};

This will lead to socket initialized once so the component that needs it can fire an emit or listen to it immediately.

and to use it:

import {socket} from"/App";

constOtherComponent = () => {
    useEffect(() => {
        socket.on("Application wide event", callback)
        return() => {
            socket.off("Application wide event");
        }
    }, [])
}

I still wondering if this is a conventional practice but it works on me, I will follow this question, maybe someone knows a better conventional practice.

Post a Comment for "Where To Put Your Websocket In React"