Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate socket.io listener when using useEffect

React.useEffect(() => {
    socket
      .on(conversationName, (message) => {
        // push into list messages a new one 
      });
  }, [conversationName]);

When user chose a conversation on the sidebar, a conversation name will be sent back from backend and stored in React state called conversationName. I used an useEffect to catch that change

Also a socket is listening on event name conversationName to get new messages.

My problem is the message that user sent will be duplicated n times when he switch back to a specific conversation n times

For example, there are 2 conversations called A and B. He clicks to A, chit chat some messages, clicks to B and then clicks back to A. Any message he sent from now on is duplicated 2 times.

Looking for some advice, many thanks guys !

like image 293
Ted Vu Avatar asked Feb 25 '26 07:02

Ted Vu


1 Answers

You need to clean up the listener when the effect fires again:

React.useEffect(() => {
    const listener = (message) => {
      // push into list messages a new one 
    };
    socket.on(conversationName, listener);

    return () => socket.off(conversationName, listener);
  }, [conversationName]);
like image 188
backtick Avatar answered Feb 28 '26 08:02

backtick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!