Search code examples
react-nativenavigationstacksettimeoutuse-effect

React-Native navigation jumps to wrong screen with useEffect and setTimeout


I have a navigation stack with different screens that I wan't to render after each other. I set the timeout to be 5 seconds, so it will go to the next screen in the stack.

<Stack.Screen name="StoryScreenOne" component={StoryScreenOne} />
<Stack.Screen name="StoryScreenTwo" component={StoryScreenTwo} />
<Stack.Screen name="StoryScreenThree" component={StoryScreenThree} />

My timeout function is this

useEffect(() => {
        setTimeout(() => {
            props.navigation.navigate('StoryScreenTwo');
        }, 5000);
    });

The problem is that if I am at screen two and navigate back to screen one, the next screen that renders is screen three, not screen two as I want it to be.

Any tips for this?


Solution

  • If i understand when you arrive on the screen two there's an other useEffect like this:

    useEffect(() => {
        setTimeout(() => {
     props.navigation.navigate('StoryScreenThree');
            }, 5000);
        });
    

    I think the setTimeout is still running so if you want to rerender screen 2 on goBack you need to use a clearTimeOut when you press the back button. Look a this : https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals But your first screen will not unmount when you go navigate so you need to use a listener to relaunch the UseEffectlike this :

    import { useFocusEffect } from '@react-navigation/native';
    
    function Profile() {
      useFocusEffect(
        React.useCallback(() => {
          // Do something when the screen is focused
    
          return () => {
            // Do something when the screen is unfocused
            // Useful for cleanup functions
          };
        }, [])
      );
    
      return <ProfileContent />;
    }
    

    more info here : https://reactnavigation.org/docs/navigation-lifecycle/