skip to Main Content

FlatList optimization:

Should I wrap all functions passed in FlatList in useCallback() hook ?

From the official doc

https://reactnative.dev/docs/optimizing-flatlist-configuration#avoid-anonymous-function-on-renderitem

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


  1. 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 ()=>({})

    
     <FlatList
        data={uiStore.data}
        ref={flatListRef}
        getItemLayout={getItemLayout}
        ListHeaderComponent={listHeaderComponent}
        renderItem={(item)=> renderItem(item)} // avoid this
        keyExtractor={keyExtractor}
     />
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search