0

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?

SARIM
  • 992
  • 3
  • 14
  • 22
  • Move the `getBurgerToken` function call, the conditional checking the token and the state setting into a `useEffect` hook. – ivanatias Dec 05 '22 at 16:02
  • Does this answer your question? [componentDidMount equivalent on a React function/Hooks component?](https://stackoverflow.com/questions/53945763/componentdidmount-equivalent-on-a-react-function-hooks-component) – CertainPerformance Dec 05 '22 at 21:45

3 Answers3

0

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!!!
}, [])
BigPun86
  • 2,480
  • 2
  • 25
  • 49
0

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.

tripp
  • 128
  • 5
0

The below might help

useEffect(() => {
   if (if_token){
      SetTokenExist(true);
   }
 }, []);
Sourav Dey
  • 1,051
  • 1
  • 13
  • 21