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
You will need to handle the function call within useEffect where you do something like this:
If you set the any state within someFunction and it still causes re-render you should use someFunction with useCallback:
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:
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.
The below might help