1

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).

CC BY-SA 4.0
1
  • 1
    Currently, you are subscribing to the event in every rerender. To do it only on the first render you need to put it in a useEffect hook. It will be like this: useEffect(() => { /* Your Code */ }, []). Jul 27, 2020 at 20:24

1 Answer 1

2

You can use useEffect hook.

function WhiteBoardArea(props) {
  // Declare useStates here

  useEffect(() => {
    socket.on("canvas-change", newCanvasData =>  {
      setCanvasData(newCanvasData)
    });
    return () => {
      socket.off("canvas-change");
    }
  }, []);

  //return something
};

Passing an empty array as an second argument to useEffect is equivalent to componentDidMount in React class components, where returned function is for componentDidUnmount.

CC BY-SA 4.0
7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.