skip to Main Content

I’m building a chat app with React Native. To render messages i’m using <FlatList. I’ve noticed a performance issues if the message list is too long. My idea is to trim newer messages when user scrolls up, and load them again from backend, when user scrolls down. So far I managed to achieve this only with the older messages by using onEndReached={loadOlder}

<FlatList
 data={messagesRendered}
 ...
 onEndReached={loadOlder}
 onOtherEndReached={loadNewer}

is there is an option to track if user scrolls back to the beginning of the list and turn this pseudo-code onOtherEndReached=.. into a real one?

Also any other suggestions on how to deal with the long lists are welcome

2

Answers


  1. There isn’t a prop from Flatlist that supports this but it can be achieved by using the onScroll prop and checking the scroll value from the event.

    const onScroll = (event) => {
      const { contentOffset } = event.nativeEvent;
    
      if (contentOffset.y === 0) {
        // User has scrolled to the very top
        loadNewer()
      }
    };
    
    return (
      <View>
        <FlatList
          onScroll={onScroll}
        />
      </View>
    );
    

    Faster list performance

    For your use case it might be worth checking out a recycler list such as Shopify’s FlashList which can improve performance compared to React Native’s FlatList.

    Login or Signup to reply.
  2. This feature is called Pull to Refresh, and it’s in the official React Native documentation. (https://reactnative.dev/docs/flatlist)
    Check out the onRefresh and refreshing props.

    Check the Example here, where it uses those props but for ScrollView (they work the same, though).

    So you can use test that code, change ScrollView with FlatList (props remain the same), and change the setTimeout(...,2000) with your code that fetchs newer items.

    Note: Shopify FlashList mentioned by MK de Silva seems to accept the same mentioned props for Pull to Refresh (here)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search