useEffect runs infinitely when using setState inside of it

43 Views Asked by At

I am working on a group video chat. I am having an issue about using useEffect. Let me explain the problem. Here's my code that runs inside a useEffect.

useEffect(() => {
  const callOthers = async () => {
    if (callOthersTriggered) {
      const selfStream = await getMedia();
      setPeersOnConference((prev) => ({ ...prev, [peer.id]: selfStream }));
      for (const remotePeer in peersOnConference) {
        if (remotePeer === peer.id) continue;
        const call = peer.call(remotePeer, selfStream);
        call.on('stream', (remoteStream) => {
          setPeersOnConference((prev) => ({
            ...prev,
            [call.peer]: remoteStream,
          }));
        });
      }
    }
  };
  callOthers();
}, [callOthersTriggered, peer, peersOnConference]);

I want to run the code snippet only when the callOthersTriggered value is true. Also I am iterating the keys of the peersOnConference object and setting the values of the keys simultaneously. For that purpose I needed to add this object in the dependency array which actually causing the infinite loop. What changes should I make to fix this issue and also achieve the functionality? Any help or idea will be appreciated.

1

There are 1 best solutions below

0
BetterReact Developer On

Remove peersOnConference from the dependency list. as it causes the useEffect to run again and again when you are doing setPeersOnConference inside the useEffect. so the code will become

useEffect(() => {
  const callOthers = async () => {
    if (callOthersTriggered) {
      const selfStream = await getMedia();
      setPeersOnConference((prev) => ({ ...prev, [peer.id]: selfStream }));
      for (const remotePeer in peersOnConference) {
        if (remotePeer === peer.id) continue;
        const call = peer.call(remotePeer, selfStream);
        call.on('stream', (remoteStream) => {
          setPeersOnConference((prev) => ({
            ...prev,
            [call.peer]: remoteStream,
          }));
        });
      }
    }
  };
  callOthers();
}, [callOthersTriggered, peer]);