GoogleChromeLabs / react-adaptive-hooks

Deliver experiences best suited to a user's device and network constraints

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Too many re-renders. React limits the number of renders to prevent an infinite loop

j4gd33p opened this issue · comments

I Implemented effectiveConnectionType to detect the network signal strength. When I call the function may be its going in infinite loop and returning following error in console:

image

Its going multiple times in switch cases. This is my function:


 const MeasureConnectionSpeed = () => {
     const { effectiveConnectionType } = useNetworkStatus();
      switch(effectiveConnectionType) {
        case 'slow-2g':
              setNetworkStrength("WEAK");
          break;
        case '2g':
              setNetworkStrength("OKAY");
          break;
        case '3g':
              setNetworkStrength("GREAT");
          break;
        case '4g':
              setNetworkStrength("EXCELLENT");
          break;
        default:
          break;
      }
  }
  MeasureConnectionSpeed();

If you call this method in react functional component it will run on each render on setting a state inside it is invoking another render and this cycle goes on. Thus, you got these re-renders warning as react stops it to prevent infinite loop.

A simple solution would be to use this method inside useEffect and required dependencies so it can only be trigger when needed instead of at every render.

I hope it helps.