FlatList optimization:
Should I wrap all functions passed in FlatList
in useCallback()
hook ?
From the official doc
described about using useCallback
only for:
renderItem={renderItem}
keyExtractor={keyExtractor}
but I wonder should I wrap getItemLayout
and listHeaderComponent
also:
<FlatList
data={uiStore.data}
ref={flatListRef}
getItemLayout={getItemLayout}
ListHeaderComponent={listHeaderComponent}
renderItem={renderItem}
keyExtractor={keyExtractor}
/>
I wan’t to increase performance of my app
2
Answers
You can wrap
getItemLayout
but there wont be any crucial performance gain and it may cause incorrect layout.Avoid anonymous function means you should not pass arrow functions
()=>({})
The decision to use useCallback for functions like getItemLayout and ListHeaderComponent in a FlatList component depends on whether these functions have dependencies that might trigger unnecessary re-renders.
The key takeaway from the official documentation is to avoid anonymous functions in renderItem and keyExtractor because creating new functions on each render can cause unnecessary re-renders of child components. This advice is specifically focused on the renderItem function, which is called for each item in the list and can significantly impact performance if not memoized.