Search code examples
react-navigationreact-navigation-stack

Conditionally rendering Navigator in v5


Any reason not to conditionally render some Navigator in react-navigation v5?

When looking at the documentation for the Auth flow, everything is done to make sure the Navigator is always rendered. Is it a bad idea to mount/unmount Navigators?

For example, is it ok to do this:

<>
      {isLoading ? (
        <SplashScreen/>
      ) : (
        <NavigationNativeContainer>
          {userToken ? <HomeStackNavigator/> : <SignInStackNavigator/>}
        </NavigationNativeContainer>
      )}
</>

instead of this:

<NavigationNativeContainer>
  <Stack.Navigator>
          {isLoading ? (
            <Stack.Screen name="Splash" component={SplashScreen}/>
          ) : state.userToken === null ? (
            <Stack.Screen name="SignIn" component={SignInScreen}/>
          ) : (
            <Stack.Screen name="Home" component={HomeScreen}/>
          )}
  </Stack.Navigator>
</NavigationNativeContainer>

Solution

  • It's okay to do it this way, but keeping the same navigator will animate any state changes, e.g. when user signs in, the Home screen will animate in. Changing the navigator means getting rid of previous navigator's state and using a new navigator.

    You can also keep the Splash screen outside the navigator and only keep SignIn and Home screen in the stack navigator. Depends on how you want the animations to look.