6

Suppose I have two screens:

  • Screen A
  • Screen B

I am initially landed on Screen A. When I click on a Button I navigate to Screen B. When I press Back Button, I am again navigated to Screen A.

I want to call an action creator when I am navigated to Screen A as mentioned in above scenario.

I just want to know that which lifecycle event will be called every time when a screen is presented.

Isn't there some event like componentWillAppear()?

Note: I am using react-native with react-navigation for navigation.

Val
  • 21,938
  • 10
  • 68
  • 86
Vishal
  • 6,238
  • 10
  • 82
  • 158
  • *which lifecycle event will be called every time when a screen is presented* **render**. But you can use `componentDidMount` – Rajesh Dec 04 '17 at 06:31
  • @Rajesh Are you sure that componentDidMount will always be called when I goBack to view? – Vishal Dec 04 '17 at 06:32
  • If the component is rendered again, yes. If you are using css to show/hide, then not sure. – Rajesh Dec 04 '17 at 06:33
  • @Rajesh I am not using css but I use react-navigation to navigate between the screens – Vishal Dec 04 '17 at 06:34
  • Just check, on back button, if the screenA's render is called ot not. If not, you might have to pass a callback for back button. – Rajesh Dec 04 '17 at 06:35
  • @Rajesh Thanks for helping. I got my answer. – Vishal Dec 04 '17 at 06:37
  • In Stack Navigation, when you go from screen A to Screen B, A never gets unmounted and hence doesn't hvae to mount again when it comes back from B. – James Poulose Aug 10 '20 at 15:41

3 Answers3

13

This can now be done with plain react navigation via their listeners:

In your Component A:

componentDidMount = () => {
  this._componentFocused();

  this._sub = this.props.navigation.addListener(
    'didFocus',
    this._componentFocused
  );
}

componentWillUnmount() {
  this._sub.remove();
}

_componentFocused = () => {
  this.setState({dataToShow});
}

React Navigation docs - Lifecycle

Andrew
  • 1,038
  • 11
  • 14
1

When you navigate from one screen to another, the first screen will not be unmounted, but still on the stack, just hide in the background.

What you need might be componentDidFocus, but it's currently in design not avaiable yet, see react-native open issue #51.

You can try this alternative way: react-navigation-addons. With this you can have events focus & blur which may suit your needs.

Val
  • 21,938
  • 10
  • 68
  • 86
  • Thanks. I will take a look at react-navigation-addons. Once the timeout is finished, I will mark this answer as accepted. – Vishal Dec 04 '17 at 06:38
1

If you use react-native-navigation, you can listen for appearance events: https://wix.github.io/react-native-navigation/#/screen-api?id=listen-to-visibility-events-globally

yedidyak
  • 1,964
  • 13
  • 26
  • 1
    Thanks for the answer but I do not use react-native-navigation. I use react-navigation for my navigation purposes. – Vishal Dec 04 '17 at 09:32