Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
j4gd33p opened this issue Sep 14, 2022 · 1 comment

Comments

@j4gd33p
Copy link

j4gd33p commented Sep 14, 2022

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();
@satnamsvirdi
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants