I am Building an application using React Native and the React Navigation library.
Steps to reproduce the issue
So using React Navigation 5, I built a stack navigator with two screens as follows:
const Stack = createStackNavigator();
const Nav = () => {
<Stack.Navigator
<Stack.Screen
name="A"
component={A}
/>
<Stack.Screen
name="B"
component={B}
/>
</Stack.Navigator>
}
As the screen A is the first in the navigator, it will be the first to be shown and rendered on screen. Now I want to immediately navigate to B As soon as A has rendered, so I wrote the following code in A:
useEffect(()=>{
navigation.navigate('B');
}, [navigation]);
The problem
The problem is that the screen stays stuck in A and doesn't navigate to B
Possible cause
I think that when the screen A tried to execute its useEffect code, the screen B still hasn't been loaded into the DOM of the navigator. Because when I actually tried to delay the execution of the useEffect by 2 seconds like this:
useEffect(()=>{
setTimeout(()=>{
navigation.navigate('B');
}, 2000)
}, [navigation]);
and it worked, the screen navigated from A to B! So I suppose that B had the time to be loaded into the DOM in less than 2 seconds ?
Any solution ?
So, if my assumption is right, I was wondering whether there is a formal way of checking if the screen B has been effectively loaded into the DOM of the navigator, or maybe waiting until the navigator has rendered before executing useEffect in A. Maybe there's a special react hook or library to check this kind of conditions ?
And if I'm wrong please help me !