Navigating back to an existing route with React Navigation

27 Feb 2018

By default React Navigation will add a route to the stack every time you navigate to it. This means if we press to move back and forth between our Home and Profile screens then our stack will contain multiple entries for Home and Profile. For example, we could imagine this stack looking like [Home, Profile, Home, Profile, Home].

For me this caused a bug on one of my screens with an event for an external library being called for each time the route had been added to the stack. For reference, the external library was react-native-signature-capture and it was my function called for the onSaveEvent.

With react-navigation >= 1.0.3 (1.0.3 has a fix for a bug where the screen would freeze when using key) we can supply a key attribute of the route we would like to navigate back to:

taken from the React Navigation docs

In practice this works by getting your routes key and then passing as a param to the next route.

1. Pass your key for your route:

this.props.navigation.navigate({
  routeName: 'Profile',
  params: {
    homeKey: this.props.navigation.state.key
  }
})

2. Use that key to navigate back to the existing route in your stack:

this.props.navigation.navigate({
  routeName: 'Home',
  params: { myParams },
  key: this.props.navigation.state.params.homeKey
})

A good example can be found in in the navigation playground where they manually pass the key value, ie this.props.navigation.navigate({routeName: 'Profile', key: 'A'})

Currently I prefer to use the key that is auto generated for me for example "id-1519705322567-5".