Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Navigation cache component

I am fairly new to React Native and a little confused with the following. I've set up a StackNavigator as shown

const MyProjectNavigator = StackNavigator({
  home: {screen: Other},
  latest_news: {screen: LatestNews}
}

When I want to go to a different screenm the navigation I perform is:

navigate(
  latest_news, {
    otherParams : param1
  }
); 

This works well so far.

Now, assume that the latest_news component queries a lot of data from a server when mounted, then performs lots of operations on that data, sorting by date, author, yadda yadda. This takes some time to complete.

How would you suggest I made this faster? On iOS for example i would normally keep my ViewController in memory and if it was available, display that. When using navigate(), the navigator seems to create a new instance of the component thus reloading and re-processing everything from the beginning making the users wait every time.

*TL;DR

I want to keep all the data my component has queried and processed across navigation so that the processing doesn't have to repeat constantly. I could just put the data on the global object but that doesn't sound like a good solution

Thanks a bunch.

like image 296
Return-1 Avatar asked Oct 30 '22 05:10

Return-1


1 Answers

You can use the TabNavigator instead of the StackNavigator.

TabNavigators reuse the same instances of its route items.

you can disable the visibility of the TabBar:

const TabNav = TabNavigator({
    Home: { screen: HomePage},    
    NewsFeed1: { screen: NewsFeed}  ,
    NewsFeed2: { screen: NewsFeed}  ,
    NewsFeed3: { screen: NewsFeed}  ,
     // ...
    },
    {
        navigationOptions: ({ navigation }) => ({
            tabBarVisible: false,
        }),});

and then you can navigate manually - for example with a button:

<Button title="NewsFeed1" onPress={() => this.props.navigation.navigate("NewsFeed1") }/>

Have a look at a simple example:

https://github.com/chrisdie/AwesomeNavigation/blob/master/src/tabbar2/App.js

like image 104
Christoph Diefenthal Avatar answered Jan 02 '23 19:01

Christoph Diefenthal