I am using react functional components to build a collaborative whiteboard with a chat online but I'm getting multiple console.log messages for a single message sent/received.
After some searching I found that the problem is probably because I'm not declaring my socket event listeners inside componentDidMount()
or the equivalent for functional components.
My code for the whiteboard is something like this:
function WhiteBoardArea(props) {
// Declare useStates here
socket.on("canvas-change", newCanvasData => {
setCanvasData(newCanvasData)
});
//return something
};
How can I properly set up this socket.on() method so that it is only run once? (the first time the component is rendered).
useEffect
hook. It will be like this:useEffect(() => { /* Your Code */ }, [])
.