skip to Main Content

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?

3

Answers


  1. You will need to handle the function call within useEffect where you do something like this:

    useEffect(() => {
      if(token){
        someFunction()
      }
    }, []}
    

    If you set the any state within someFunction and it still causes re-render you should use someFunction with useCallback:

    const someFunction = useCallback(() => {
      // someFunction stuff!!!
    }, [])
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. The below might help

    useEffect(() => {
       if (if_token){
          SetTokenExist(true);
       }
     }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search