July 9, 2019

React Native Issues: How to update your state when switching screens

React Native Issues: How to update your state when switching screens

Today I encountered a small issue I could easily resolve. The app I am working on uses the react navigation library to navigate between screens in some parts of the application. In this case I had a main SwitchNavigator that makes use of several StackNavigators.

I encountered the following problem, I wanted to change the state of the component on the below level of the navigation stack once I switched to it. Since the navigation stack is just a bunch of layers on top of each other, those components are already mounted.

import { withNavigation } from "react-navigation"

class myComponent {...}

export default withNavigation(myComponent)

The simple solution was to use the HOC withNavigation provided by react navigation. Once you wrap your component you can use the onFocus prop to check if your component is focused or not. With that prop you can then trigger the state change or whatever it is you want to execute once the component is on focus, now when switching between your screens in the stack you can simply update your component state.