Flatlist getItemLayout usecase

Rajat Gupta picture Rajat Gupta · Feb 8, 2018 · Viewed 16.8k times · Source

Why we use getItemLayout in flatlist ,how it help to improve performance of a flatlist .check the react-native docs but didn't find a satisfying answer.

  getItemLayout={(data, index) => (
    {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}
  )}

what is offset here ,what it does?

Answer

jevakallio picture jevakallio · Feb 8, 2018

React Native FlatList optimises list view performance by only rendering rows that are currently visible on the screen, and unmounting rows that have been scrolled past.

In order for FlatList to be able to do this, it needs to know the total height of the rows above the currently visible viewport, so it can set the underlying ScrollView scroll position correctly.

There are two ways for FlatList to achieve this. Either,

  • it can calculate the heights of the rows after the rows have been mounted, or
  • you can tell it how tall you expect the rows to be.

In the former case, it needs to to fully layout, render, mount and measure the previous rows need until it is able to calculate the position of the next rows.

In the latter, it can precalculate the positions ahead of time and avoid the dynamic measurement cost.

The three arguments to the getItemLayout callback are:

  • length: Height of each individual row. They can be of different heights, but the height should be static. The optimizations work best when the height is constant.
  • offset: The distance (in pixels) of the current row from the top of the FlatList. The easiest way to calculate this for constant height rows is height * index, which yields the position immediately after the previous row.
  • index: The current row index.

If the FlatList is horizontal, the each column is treated list a list row, and the column width is the same as row height.