'React-Native (FlatList) Switching between Grid and List View is re rendering the header each time

I have a flatlist that when I click a button switches between grid and list view. The problem is in my FlatList I have a ListHeaderComponent which re renders each time I switch between the two and I don't want it to re render.

Also, I can't place the Header outside the flatlist since I need it to scroll and I can't wrap all screen with a ScrollView The FlatList rerenders when isGrid is changed How can I solve it ?

Here is my implementation:

FlatList Component:

<SafeAreaView style={styles.screen}>
  <FlatList
    ref={flatListRef}
    data={ads}
    numColumns={isGrid ? 2 : 1}
    key={isGrid ? 1 : 0}
    nestedScrollEnabled
    columnWrapperStyle={isGrid ? styles.grid : null}
    initialScrollIndex={0}
    onEndReachedThreshold={0.5}
    onEndReached={onEndReached}
    ListHeaderComponent={Header}
    keyExtractor={(item) => item?._id}
    showsVerticalScrollIndicator={false}
    ListHeaderComponentStyle={HeaderStyle}
    ListFooterComponentStyle={footerStyle || styles.footerStyle}
    renderItem={({ item, index }) =>
      isGrid ? (
        <AdCard
          ad={item}
          onPress={() => goToDetails(item?._id, index)}
          containerStyle={styles.gridCardStyle}
        />
      ) : (
        <AdsCard
          ad={item}
          onPressThreeDot={onPressThreeDot}
          onPress={() => goToDetails(item?._id, index)}
          isList={true}
          containerStyle={styles.adCard}
        />
      )
    }
    ListEmptyComponent={loading ? loadingPlaceholder : noAdsComponent}
    contentContainerStyle={
      isGrid ? styles.gridStyle : styles.contentContainerStyle
    }
    getItemLayout={(d, index) => {
      return isGrid
        ? { length: hp(250), offset: index * hp(250), index }
        : { length: hp(348), offset: index * hp(348), index };
    }}
    ListFooterComponent={<AdsEndMessage isLoading={loading} />}
    refreshControl={
      <RefreshControl
        refreshing={isRefreshing}
        onRefresh={onRefresh}
        tintColor={BURNING_ORANGE}
        colors={[BURNING_ORANGE]}
      />
    }
  />
</SafeAreaView>

Header Component (passed as a prop to the flatlist):

<SafeAreaView style={styles.container}>
  {bannerAds?.length > 0 && <BannerAds bannerAds={bannerAds} />}
  <SectionHeader sectionStyle={styles.sectionStyle} />
  <HomeAdsTab />
  <View style={styles.toggleView}>
    <Text style={styles.title}>{t('common.tazweed-marketplace')}</Text>
    <ToggleGridOrList />
  </View>
</SafeAreaView>

Thank you in Advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source