Virtualized list rendering

You render fixed-height rows efficiently with FlatList so the paged restaurant screen stays responsive as customers scroll.

Learning outcomes

  • Explain how FlatList uses virtualization to render long lists efficiently.
  • Use stable keys, useCallback and React.memo to reduce unnecessary row rendering.
  • Configure getItemLayout for fixed-height rows and guard infinite-scroll requests against duplicates.
  • Handle loading, empty, error and refresh states without replacing existing data unnecessarily.
  • Use SectionList to render grouped menu items with sticky section headers.
Prerequisite conceptsInfinite query

The restaurant list contains 50 seeded restaurants, fetched in pages of 20. Rendering every restaurant inside a ScrollView becomes increasingly expensive as more pages arrive. You need a list that renders the visible rows without creating a native view for every restaurant.

The menu screen has a related problem. Its items belong to sections, and customers need to see the current section header while scrolling. React Native provides two list components for these cases: FlatList and SectionList.

ScrollView and list rendering

A ScrollView renders all its children at once. This is similar to using items.map() inside a web page and letting the browser scroll through the resulting elements.

For a small settings screen, that approach is fine. For a restaurant list that grows as customers load more pages, it creates unnecessary work. Every row becomes a native view, even when it is far outside the visible area.

FlatList handles this differently.

Virtualization

Virtualization means rendering only a window of items around the visible area. Rows that move sufficiently far outside that window can be unmounted.

This limits how many native views the app needs to maintain while the customer scrolls. A list with hundreds of restaurants does not need to keep every restaurant row mounted simultaneously.

FlatList provides several properties for controlling its rendering window:

PropertyPurposeDefault
initialNumToRenderNumber of rows rendered initially10
windowSizeRendering window measured in screen heights21
maxToRenderPerBatchNumber of new rows rendered in each batchLibrary default

The default windowSize of 21 represents the visible screen plus approximately 10 screen heights above and below it.

You can tune these values when measurements show a problem. Rendering too many rows increases memory and rendering work. Rendering too few can leave blank areas during fast scrolling.

For this week's 50 restaurants, the defaults are a reasonable starting point.

Stable row identity

Every list row needs a stable identity. FlatList uses keyExtractor to obtain that identity from each item.

For the restaurant list, use the restaurant id:

tsx
<FlatList
  data={restaurants}
  keyExtractor={restaurant => String(restaurant.id)}
  renderItem={renderItem}
/>

The restaurant id identifies the record, regardless of where it appears in the array.

Avoid using the array index as the key. When records are inserted or removed, subsequent indices change. React can then associate existing component state with the wrong restaurant.

A stable key tells React which record a row represents, rather than where that record happens to be positioned.

Stable callbacks and memoised rows

FlatList can render rows again when their props change. Function references are one source of unnecessary changes.

Consider an inline callback:

tsx
<FlatList
  data={restaurants}
  renderItem={({ item }) => (
    <RestaurantRow
      restaurant={item}
      onPress={() => openRestaurant(item.id)}
    />
  )}
/>

Every render creates new function references. When another page arrives, the parent screen renders again, and visible rows can receive different callback props despite having unchanged restaurant data.

Use useCallback to keep the callback references stable:

tsx
const open = useCallback((id: number) => {
  router.push({
    pathname: "/restaurant/[id]",
    params: { id: String(id) },
  });
}, []);

const renderItem = useCallback(
  ({ item }: { item: Restaurant }) => (
    <RestaurantRow restaurant={item} onPress={open} />
  ),
  [open],
);

The row component can also use React.memo:

tsx
export const RestaurantRow = memo(function RestaurantRow({
  restaurant,
  onPress,
}: Props) {
  return (
    <Pressable onPress={() => onPress(restaurant.id)}>
      <Text>{restaurant.name}</Text>
    </Pressable>
  );
});

React.memo can skip rendering when the component receives the same props. Combined with stable callback references, this prevents unchanged rows from rendering again merely because another page was appended.

There is an important condition: memoization helps when the props remain stable. If you create new objects or functions on every render, the row can still render again.

Fixed-height row layout

FlatList normally measures rows to determine their positions. When row heights are fixed, you can provide those measurements through getItemLayout.

The restaurant row has a fixed height of 76 dp. That includes its bottom border.

tsx
const ROW_HEIGHT = 76;

<FlatList
  data={restaurants}
  getItemLayout={(_, index) => ({
    length: ROW_HEIGHT,
    offset: ROW_HEIGHT * index,
    index,
  })}
/>

For a row at index 5, the offset is:

76 * 5 = 380 dp

FlatList can use these measurements without first rendering and measuring every preceding row. This also helps operations such as scrollToIndex locate rows that are not currently rendered.

The measurements must match the actual layout.

If the row is 76 dp high and you add a separate 1 dp separator, the actual distance between row starts becomes 77 dp. An offset calculated as 76 * index will be too small.

The restaurant row therefore draws its bottom border inside its fixed 76 dp height. A separate separator would change the measurements and make the supplied offsets incorrect.

Infinite scrolling

The restaurant screen uses an infinite query to load pages from the API as the customer approaches the end of the list.

FlatList provides onEndReached for this purpose. Its onEndReachedThreshold determines how close to the end the customer must scroll before the callback fires.

The restaurant list uses:

tsx
<FlatList
  data={restaurants}
  onEndReached={loadMore}
  onEndReachedThreshold={0.5}
/>

A threshold of 0.5 means loading starts when the customer approaches within half a screen height of the end.

This gives the API time to return the next page before the customer reaches the last row.

Duplicate request protection

onEndReached is not guaranteed to fire only once. It can fire multiple times around the same list boundary. It can also fire when the list first mounts if the initial page does not fill the screen.

The callback must check the query state before requesting another page.

Two properties matter:

  • hasNextPage indicates whether another page exists.
  • isFetchingNextPage indicates whether a next-page request is already running.

The request should run only when the first condition is true and the second is false.

tsx
const loadMore = useCallback(() => {
  if (query.hasNextPage && !query.isFetchingNextPage) {
    void query.fetchNextPage();
  }
}, [query]);

This prevents repeated end-of-list events from starting overlapping next-page requests. The empty next_cursor on the final API page means no next page exists.

Loading and refresh states

A list screen has several states beyond successful data rendering. Each one needs a different presentation.

Initial loading

The first request has no restaurant data yet. Display eight skeleton rows while it is pending.

The skeletons resemble the final rows, so the screen does not have to replace a completely different layout when the response arrives.

Pull to refresh

React Native's RefreshControl provides the native pull-to-refresh interaction.

The refreshing state should reflect a background refetch, not a request for another page:

tsx
<RefreshControl
  refreshing={query.isRefetching && !query.isFetchingNextPage}
  onRefresh={() => void query.refetch()}
/>

If you use isFetching alone, loading another page can activate the pull-to-refresh spinner. The top spinner and footer spinner represent different operations.

Empty state

FlatList provides ListEmptyComponent for an empty data array.

The empty state should be centred rather than sitting at the top of a short content area. Set the content container's flexGrow to 1 when the list is empty.

Loading the next page

Use ListFooterComponent for the next-page spinner. It appears below the existing restaurants while another page loads.

The existing rows stay visible, so customers can continue reading while the request completes.

Error state

An initial request failure and a background refetch failure should not produce the same screen.

When there is no data and the first request fails, display a full-screen error with a Try again button.

When a background refetch fails, keep displaying the existing restaurants. A query can have both previous data and an error, and replacing its data with an error screen would discard information the customer can still use.

SectionList for grouped menus

The restaurant menu is grouped into sections rather than displayed as one flat array.

SectionList is FlatList's sibling for this structure. It accepts an array of sections, each containing a title and a data array.

For example, the menu transformation produces a structure like:

tsx
const sections = [
  { title: "Menu", data: menuItems },
];

The screen renders each section with a header and its items:

tsx
<SectionList
  sections={sections}
  keyExtractor={item => String(item.id)}
  stickySectionHeadersEnabled
  renderSectionHeader={({ section }) => (
    <Text>{section.title}</Text>
  )}
  renderItem={({ item }) => <MenuRow item={item} />}
/>

With stickySectionHeadersEnabled, the current section header remains pinned at the top while its items scroll underneath it.

SectionList uses virtualization like FlatList. You do not need to put every menu item inside a ScrollView to display grouped content.

The menu exercise supplies sections in { title, data } form. The Week 2 API does not send categories, so the current seed uses one fallback section named "Menu". The same screen can display real categories later when the API provides them.

Performance measurement

Do not tune list properties based only on intuition. Measure the scrolling behaviour first.

In the Expo development environment, open the dev menu by pressing m in the terminal and enable the performance monitor. Observe JavaScript and UI frame rates while scrolling.

Development builds include additional checks and an unoptimised bundle. Judge the final scrolling experience on a release build as well.

Restaurant and menu screens

The restaurant screen combines virtualization, stable row rendering and cursor-based pagination. FlatList handles the visible rows, while the query supplies additional pages as the customer scrolls.

The menu screen uses SectionList because its data is grouped into sections with sticky headers. Both screens rely on virtualized rendering rather than mounting every row inside a ScrollView.

Keep the list components focused on presentation. The query manages pages, the data helpers prepare the records, and the row components display individual items.

Check your understanding

Question 1 of 4

The restaurant list grows from 20 to 100 items as the customer loads more pages. Why is FlatList preferable to rendering every item inside a ScrollView?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (React Native 0.88).

Finished Lesson 4.9?