avatarSudipti Ranjan

Summary

The article compares FlatList and ScrollView in React Native, discussing their use cases, performance implications, and features.

Abstract

In mobile app development with React Native, choosing the right component for displaying scrollable lists is crucial for performance and user experience. The article "Decoding FlatList vs ScrollView" delves into the differences between FlatList and ScrollView. It explains that ScrollView renders all items at once, making it suitable for small datasets, while FlatList efficiently renders only visible items, ideal for large datasets. The author highlights the benefits of FlatList's performance optimization, such as virtualization, pagination, and dynamic rendering, which contribute to a smoother user experience in apps with extensive lists. Additionally, the article provides code examples and discusses advanced customization, animations, and the pull-to-refresh feature, offering developers insights into when and how to implement each component effectively.

Opinions

  • The author suggests that for small, static datasets, ScrollView is a straightforward and suitable choice.
  • FlatList is recommended for dynamic data or extensive lists due to its efficiency in managing memory and reducing load on the app.
  • The article conveys that FlatList's ability to render items on-demand as the user scrolls makes it superior for large datasets, preventing performance issues associated with ScrollView's rendering of all items simultaneously.
  • Customization options, such as styling and animations, are presented as advantages of using FlatList over ScrollView.
  • The author emphasizes that while ScrollView lacks the virtualization features of FlatList, it remains a valid option for scenarios with a limited number of items, offering a simple approach to content rendering.
  • The conclusion of the article reiterates that the choice between FlatList and ScrollView should be based on the specific requirements of the app, with FlatList being the go-to for larger lists due to its efficiency and intelligent loading capabilities.

Decoding FlatList vs ScrollView

For a smooth user experience

Photo by Ion (Ivan) Sipilov on Unsplash

When we want to display a list of items that can be scrolled in mobile apps, we use components designed for this purpose. React Native, a popular javascript mobile-based framework has provided us with such components as ScrollView and FlatList.

However, every developer encounters the dilemma of choosing between reliable ScrollView and dynamic FlatList to display content.

Consider a news application where you have to present a list of articles to your users. As the number of articles grows, you find yourself questioning between the efficiency of FlatList and the simplicity of ScrollView and on what points you should differentiate between both.

Well, I have got you covered!

Let’s go through these two components in detail:

ScrollView:

Think of a container that can hold various elements like a list of books, images, and so on, allowing users to scroll through them from a mobile view.

ScrollView is a react native component that shows all its items simultaneously, and you can scroll vertically and horizontally (by setting the horizontal property).

  • It renders all items at once, regardless of whether they are visible or not on the screen. Hence, it is reliable for small datasets.

Req Props for Scrollview:

Children: Accept the components or views that you want to scroll.

You can use Scrollview by wrapping your view or components inside it. For example:

<ScrollView>
      <View style={{ flex: 1 }}>
        <Text style={{ fontSize: 24, fontWeight: 'bold' }}>Welcome to My List</Text>
        <Text>some content inside the ScrollView.</Text>
        <Text>More content goes here...</Text>
         ......
      </View>
    </ScrollView>

Flatlist:

As our app grows and we get longer lists to show, we want something more efficient that manages memory and has less load on our app.

That’s where FlatList comes into play. It’s like an intelligent scrollable list that renders only the items currently visible on the screen. As the user scrolls, FlatList updates the displayed items, showing up new items as they come into view and removing items that move out of view.

FlatList is a React Native component that efficiently displays only the visible items on the screen.

  • It renders only the items currently in the user’s view, making it highly efficient for large datasets.
  • It requires an array of data, and through the renderItem(Prop) callback, you can manipulate how each item in the array is presented.

Req Props for FlatList :

Data: Takes an array of all items to be shown.

renderItem: Allows you to design a particular component for each item.

<FlatList
      data={yourDataArray} //items to be displayed
      renderItem={yourRenderItemFunction} 
      keyExtractor={(item) => item.id.toString()}// Extracts a unique key for each item.
      horizontal={false} // Set to true for horizontal scrolling
      showsHorizontalScrollIndicator={false} //visibility of the scroll indicators.
      showsVerticalScrollIndicator={true}
      numColumns={1} // Change to the desired number of columns for a grid layout
      onEndReached={loadMoreData} //Used for pagination.
      onEndReachedThreshold={0.1} //Used for pagination.
      // Other FlatList Props...
/>

so far we have learnt, For a small, static dataset, ScrollView would be handy. However, for dynamic data or extensive lists, opting for the efficiency of FlatList is a wise decision.

Let’s overview some of the “FlatList Properties:

List of languages displayed in a Flatlist

1. Advanced Customization:

You can make your list look cooler by changing how each item looks, or you can provide users with the ability to refresh the displayed data manually. Let’s look into the code for both.

- Styling Options:

Enhance FlatList items with custom styles based on conditions, such as. highlighting specific.

const renderItem = ({ item }) => (
//highlighting specific items
  <View style={{ backgroundColor: item.isHighlighted ? 'yellow' : 'white', padding: 10 }}>
    <Text style={{ fontSize: 16 }}>{item.title}</Text>
  </View>
);

- Pull-to-Refresh:

Implement a pull-to-refresh functionality for your FlatList, allowing users to refresh the displayed data manually.

<FlatList
  data={data}
  renderItem={renderItem}
  keyExtractor={(item) => item.id}
  onRefresh={handleRefresh} // add PulltoRefresh logic
  refreshing={isRefreshing}
/>

2. Performance Optimization:

When you have a lot of items on your list, you want it to work fast. You can load a few items at a time as you scroll down, so it doesn’t get slow and works smoothly.

- Large Datasets:

Optimize performance with large datasets by chunking the data and dynamically loading more as the user scrolls.

const largeData = demoArray(data, 10);
<FlatList
  data={largeData[currentData]}
  renderItem={renderItem}
  keyExtractor={(item) => item.id}
  onEndReached={loadMoreLargeData}
  onEndReachedThreshold={0.1}
/>

- shouldComponentUpdate or React.memo:

Improve rendering efficiency using React.memo or shouldComponentUpdate for the FlatList component.

// Using React.memo to memoize the FlatList component
const MemoizedFlatList = React.memo(FlatList);
<MemoizedFlatList
  data={data}
  renderItem={renderItem}
  keyExtractor={(item) => item.id}
/>

3. Animations:

You can add a fancy entrance for each item in your list by adding animations or dynamic transitions.

- Integrating Animations:

Incorporate animations, such as fade-in effects, to enhance the visual appeal of your FlatList.

- Dynamic Transitions:

Apply dynamic transitions, like adjusting item height with animations, for a more interactive user experience.

import { Animated, FlatList, Text } from 'react-native';
const fadeIn = new Animated.Value(0);
const fadeInAnimation = () => Animated.timing(fadeIn, { toValue: 1, duration: 500, useNativeDriver: true }).start();
const renderItem = ({ item }) => (
  <Animated.View style={{ opacity: fadeIn, height: animatedHeight }}>
    <Text>{item.title}</Text>
  </Animated.View>
);
<FlatList
  data={data}
  renderItem={renderItem}
  keyExtractor={(item) => item.id}
  onLayout={fadeInAnimation}
/>

4. Pagination:

It’s like turning the page in a book to see what happens next. So, When you scroll to the bottom of your list, it magically loads more items.

- Loading More Data:

Implement pagination in FlatList to load additional data as the user reaches the end of the list.

<FlatList
  data={data}
  renderItem={renderItem}
  keyExtractor={(item) => item.id}
  onEndReached={loadMoreData}
  onEndReachedThreshold={0.1}
/>

“Thus, FlatList stands out with its performance optimization, infinite scrolling, and navigation methods. However, it’s worth noting that ScrollView, while lacking in virtualization, can be suitable for scenarios with a limited number of items, offering a straightforward approach to rendering content.”

You can explore additional properties and customization options by referring to the official documentation.

Now, think of a book app showing a list of stories and authors. When you have only a few books, using ScrollView is like flipping through pages — it’s simple. But, as your collection grows, switch to FlatList. It’s like having an organized library, ensuring smooth scrolling and a quick, responsive experience for readers exploring a growing number of books and their authors.

Here is a simple code example of Flatlist and Scrollview:

  1. Defines an array of books with their properties.

Let’s create a list of books with properties id, title, and author.

2. Represents a single book item’s UI structure.

Let’s create a component, BookListItem, which renders the item — title and author on the UI. Now you can use this BookListItem component whenever you want to display a book in your app.

3. Renders a list of books using either FlatList or ScrollView based on the ‘isFlatList’ prop.

The BookList component takes a prop called isFlatList. It renders a list of books either using FlatList or ScrollView based on this prop. It uses the BookListItem component that we are importing here to display individual book items.

4. Through the App component, we display two instances of the BookList component, one using FlatList and the other using ScrollView.

  • Imports the book data from the ‘books’ file.
  • render data from books using the BookList component

Comparing FlatList and ScrollView:

Comparison between SL/FL based on dataset

FlatList:

  1. Efficient for large datasets.
  2. Renders only what’s visible on the screen.
  3. Requires ‘data’ and ‘renderItem’ props.
  4. Inherits features of Virtualized List and ScrollView.

ScrollView:

  1. Renders everything in the list, which can be heavy for large datasets.
  2. Requires a ‘children’ prop.
  3. Suitable for a smaller number of items.

In Conclusion:

With this, we have come to the end of this article. As discussed, the choice between SL/FL depends on your needs; use FlatList when dealing with many items. It’s efficient and only shows what you need, making your app faster.

Use ScrollView when you have a small set of items to display and don’t need the intelligent loading features of FlatList. It’s simpler but might be less efficient for large datasets.

Hence, The choice depends on the specific requirements of your app.

Thanks for reading!

React Native
Performance
App Development
React
React Native Flatlist
Recommended from ReadMedium