Search code examples
react-nativesocket.iouse-effect

Using socket.io and useEffect causing delays the more I add to an array?


The code below works but if I click the button more and more there the app freezes up and the update occurs after a delay. That delay is increased significantly after each button press.

How can I avoid this delay/freeze up?

const ContactChatScreen = ({navigation}) => {
  const mySocket = useContext(SocketContext);
  const [chatMsgs, setChatMsgs] = useState([]);

  const sendMsg = () => {
    mySocket.emit('chat msg', 'test');
  };

  useEffect(() => {
    mySocket.on('chat msg', (msg) => {
      setChatMsgs([...chatMsgs, msg]);
    });
  });

  return (
    <View style={styles.container}>
      <StatusBar
        backgroundColor={Constants.SECONDN_BACKGROUNDCOLOR}
        barStyle="light-content"
      />
      {chatMsgs.length > 0
        ? chatMsgs.map((e, k) => <Text key={k}>{e}</Text>)
        : null}
      <Text style={styles.text}>Contact Chat Screen</Text>
      <MyButton title="test" onPress={() => sendMsg()} />
    </View>
  );

Solution

  • I was able to fix this by changing this:

    useEffect(() => {
        mySocket.on('chat msg', (msg) => {
          setChatMsgs([...chatMsgs, msg]);
        });
        return () => {
          // before the component is destroyed
          // unbind all event handlers used in this component
          mySocket.off('chat msg');
        };
      }, [chatMsgs]);
    

    adding the mySocket.off was the key.