Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatlist getItemLayout usecase

Tags:

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?

like image 562
Rajat Gupta Avatar asked Feb 08 '18 06:02

Rajat Gupta


People also ask

What is getItemLayout?

getItemLayout ​ (data, index) => {length: number, offset: number, index: number} getItemLayout is an optional optimization that allows skipping the measurement of dynamic content if you know the size (height or width) of items ahead of time.

How can I make my FlatList faster?

Use basic components​ The more complex your components are, the slower they will render. Try to avoid a lot of logic and nesting in your list items. If you are reusing this list item component a lot in your app, create a component only for your big lists and make them with as little logic and nesting as possible.

What is the use of keyExtractor in FlatList?

It extracts the unique key name and its value and tells the FlatList component to track the items based on that value.


1 Answers

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.

like image 156
jevakallio Avatar answered Oct 09 '22 11:10

jevakallio