Using ScrollView
is an easy way to scroll a list, but it isn’t the most memory efficient, which can really matter for performance on devices with limited memory. We’ll switch from using ScrollView
to using FlatList
, which will reuse views, and is the preferred way of showing long scrollable lists.
Instructor: [00:00] We have a scrolling list of restaurant, but we're using a scroll view to show them. Instead, let's import FlatList from React native. Scroll view loads the entire view into memory when it mounts.
[00:12] Let's find for small number of items like we have here, but will cause memory and performance problems, if we're showing hundreds or thousands of items at a time. FlatList, however, is designed to be [inaudible] even with thousands of items, because it recycles the views which lowers the memory footprint.
[00:29] Unlike scroll view, FlatList takes a render prop for each item. Pass the filtered restaurant list into the FlatList as a prop name data. The render prop for each item is called render item.
[00:43] In the scroll view, we have each item rendered directly inline here. Let's clean that up a bit and first extract it into a new component file called restaurant row.js. There, we can import React's View, Text, and StyleSheet from React native and make our default component.
[01:03] Then, we can copy the row component and the styles as well. In this restaurant row, we use the place and the index, so we'll need to pass those in this props. Like an app.js, we can import the restaurant row and use it in the render item render prop.
[01:30] Render item takes a function and that function will get both the item and the index of the row that is being rendered. You can make a new function with item and index, and return a new restaurant row, passing in the list item as the place prop and the index as the index prop.
[01:48] As a last prop to FlatList, we have to provide a unique key for every row in the list. To set a prop called key extractor which is a function that will be passed in each item from the data.
[02:00] We need to return something unique for every row here. In our example, that will be the item's name. Now in practice, this is often a unique ID of some kind. Finally, we need to clean up this unused scroll view. Then, we can reload and see our FlatList.
[02:16] With this list, you can actually see how progressively loads the items. If I reload this simulator and pass the screen right as it loads, you can see it only loads the first 10 items and loads the rest later.
[02:30] This is part of the memory and performance saving techniques that are built in the FlatList. If we don't want that flicker of just the first 10 items loading now, we can specify a higher number.
[02:40] Let's pass an initial num to render prop to FlatList, and when we reload, there's no flicker.