links: React Native MOC


How to optimize navigation during reset?

Whenever you use navigation.reset it resets the entire stack which means it unmounts all the screens/components and remounts them.

This behavior is fine for screens with less logic, consider you have a heavy home screen with more than 1000 components this hits the performance. The usual scenario for reset would always be from the home screen. This can be optimized by skipping the render of home screen by preserving it’s state.

Consider a scenario where user has this flow

  1. Home Screen Profile Screen Reset to Cart Screen (so when navigated back you come to home screen instead of Profile) for simplicity sake. Before you say we can use replace consider the stack contains 4 to 5 screen, in that case replace won’t be of help

You can use CommonActions from react-navigation, and use navigation reset which accepts callback function with a state and returns a reset action.

navigation.reset(state => {
  // Get only home screen route (this contains key which is helpful for state)
  const routes = state.routes.filter(route => route.name === 'Home')
  routes.push({
    key: 'cart',
    name: 'Cart'
  })
  
  return Commonactions.reset({
    ...state,
    routes,
    index: 1
  })
})

Now the Home Screen will skip rendering and Profile gets unmounted and Cart gets mounted


tags: react-native react-navigation

links: