Switch Navigator
What was the purpose of Switch Navigator
?
The purpose of Switch Navigator in previous versions was to dynamically switch between screens/navigators, which is mostly useful for implementing onboarding/auth flows. For example:
export default createAppContainer(
createSwitchNavigator(
{
App: MainTabNavigator,
Auth: AuthLoadingScreen,
Login: createStackNavigator({ Login: LoginScreen }),
},
{
initialRouteName: "Auth",
}
)
);
And then after login:
navigation.navigate("App");
With React Navigation v5.x, screens can be defined, and we can alter the definitions of a navigator, which makes Switch Navigator unnecessary. We can now define the above pattern declaratively:
import React from "react";
import { useSelector } from "react-redux";
import { NavigationContainer } from "@react-navigation/native";
import { AuthNavigator, MyCustomNavigator } from "./MyCustomNavigator";
const AppNavigator = (props) => {
const isAuth = useSelector((state) => !!state.auth.access_token);
return (
<NavigationContainer>
{isAuth && <MyCustomNavigator />}
{!isAuth && <AuthNavigator />}
</NavigationContainer>
);
};
export default AppNavigator;
There were two ways to handle this in earlier versions of React Navigation,
- Keeping multiple navigators and using switch navigator to switch the active navigator to a different one upon login (recommended)
- Upon login reset the state of the navigator to the desired screens.
Both of these ways were imperative. We have to update the state of the user to save the token, and then navigate or reset to change screens manually. What happens if the user logs out? We must do the task twice already imperatively since we have to update the state in order to delete the token, then navigate or reset again manually to show the login screen. Adding more scenarios to this (e.g. unverified user, guest, etc.), and it becomes even more complicated.
But with the new approach, you can declaratively say which screens should be accessible if the user is logged in and which filters shouldn't be. Depending on the user logged in status, we can update the userToken in the state, and the correct screens are shown automatically.
To summarize the benefits:
- Correct screens are shown automatically upon login/signout.
- If the user is not logged in, it becomes impossible to navigate to screens where the user logged in was required (e.g. restoring persisted state), which means you don't need to deal with inconsistent states.
- We get smooth animations since all our screens are under the stack navigator. Switch navigator used to have an abrupt screen change behaviour.
So, we can see that the new approach covers more edge cased and removes the need for something like Switch Navigator. This is why it has been removed.
See Authentication flows for a guide on implementing authentication flows.
💌 If you’d like to receive more tutorials in your inbox, you can sign up for the newsletter here.
Discussions