Home > Software engineering >  Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. How to p
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. How to p

Time:12-06

I am defining my token check like this in bare react native. I am getting error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

const Stack = createNativeStackNavigator();
function App() {
  
  const [tokenExist, SetTokenExist] = useState(false);
  const if_token = getBurgerToken();
  if (if_token){
  SetTokenExist(true);
  }


  return (
    <NavigationContainer>
      <Stack.Navigator>

        {tokenExist ? (
          <>
            <Stack.Screen name="Home">
              {(props) => <HomeScreen {...props} Istoken={tokenExist} />}
            </Stack.Screen>
          </>
        ) : (
          <>
            <Stack.Screen name="Login">
              {(props) => <LoginScreen {...props} extraData={SetTokenExist} />}
            </Stack.Screen>
          </>
        )
        }



      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

How to tackle the issue over here?

CodePudding user response:

Add if condition inside useEffect and set dependency

CodePudding user response:

The reason React is called 'React' is because components are designed to 'react' (re-render) to state changes. So, in practice, you are executing the following:

  1. Render Stack
  2. Assuming if_token is true, change state of Stack
  3. Because React re-renders on state changes, repeat steps 1 and 2

This will continue forever as long as if_token's value doesn't change. React is smart, and instead of just freezing in an infinite loop, it throws an error informing you that there is probably an infinite loop.

As mentioned in other posts, useEffect with dependencies is a great way to implement what you are trying to do.

CodePudding user response:

The below might help

useEffect(() => {
   if (if_token){
      SetTokenExist(true);
   }
 }, []);
  • Related