← back to the blog


React Native Navigator Lifecycle Events

Posted
on March 19th, 2019 by Chanoch

When creating a react native project, you might find that local state is preserved in your screens when you navigate away and navigate back. So what's happening here?

If you add a console.log into your componentDidUnmount() you will see that it is not called. This is because the of the history support. Stack components are added into the stack without being unmounted and their state preserved.

They do receive lifecycle events related to their visibility including willBur and didBlur and willFocus and didFocus. To subscribe to these events, you need to call addListener() on the navigation prop that is received by Stack components:

  componentDidMount() {
    this.didBlurListener = this.props.navigation.addListener('didBlur', ()={
      this.setState({'resetState': true})
    }
  }

What will happen now is that each time the component/screen is navigated away from, the event handler will be called and can update the component (including in this case updating the state).

Make sure to remove the listener when the component is unmounted in order to prevent memory leaks:
componentDidUnmount() {
this.didBlurListener.remove() }

 

d