Switch Navigator in React Navigation 5

Omid Borjian
2 min readMay 11, 2021

If you’re like me and wait until the last minute to migrate to the latest version of react navigation, you’ll find yourself doing a good amount of refactoring.

I held on to V4 till the number of issues and the performance hit started to get seriously noticeable. React Navigation 5 migration (and the soon to be released 6…) is a lot of work, but trust me it’s worth it!

In addition to the fundamental approach (static vs dynamic) and APIs completely changing, there are a few concepts that no longer exist. One of them being the Switch Navigator.

Switch Navigation

The purpose of Switch Navigator is to dynamically switch between screens and navigators, mostly useful for implementing auth/onboarding flow. Going off of the migration guide, you can achieve a similar behavior using conditional loading of the screen. But not quite…

We also used it to abstract away parts of the app which are logically different (especially Redux state containers). We tried to change a bunch of the architecture but there was unexpected behavior on goBack(). So we need a better way…

Navigation Actions to the rescue

Generally Switch navigation gets rid of the state prior to your switch screen so if we can somehow “Reset” the state, we’ll have our switch. Well that’s where Navigation Actions come in. Specifically, the Common Actions. Using the reset method we can achieve our Switch behavior!

It looks lengthy so here is a helper function:

import { CommonActions } from '@react-navigation/native';function SwitchNavigation(name, params, navigation) {  navigation.dispatch(
CommonActions.reset({
index: 1,
routes: [
{ name: name, params: params || {} },

],
})
);
}

And here is how you can use it:

Most common use:
SwitchNavigation('App', {user : 'Omid'}, this.props.navigation);
If you only have a nav Ref
SwitchNavigation('App', {user : 'Omid'}, navigationRef.current?);

That’s it!

--

--

Omid Borjian

Hi! My name is Omid and I’m a remote work enthusiast