Search code examples
react-nativereact-native-flatlistreact-virtualizedreact-native-sectionlist

Large components as sections in VirtualizedList/etc?


If I want to display a bunch of heterogenous data in a virtualized list, it seems like the default way to do it is have the parent component gather up all the data so that it can create the sections to supply to the list component.

Is there any way to avoid requiring the parent component from doing this? I'd like to decouple the parent component from the data gather part, so that all it has to do is declare it has such and such components, and then those components would be responsible for gathering the data.

This would be exceedingly simple if it were a ScrollView:

<ScrollView>
    <SectionA>
    <SectionB>
    <SectionC>
</ScrollView>

However, to leverage the performance gains of a VirtualizedList, if each section is large, I would need to pass in the individual data of each section into the VirtualizedList. I'm not sure how to do this or if it's possible.


Solution

  • Not sure if this is idiomatic or a gross React anti-pattern, but the way I solved it was to implement each section as purely headless data Component.

    export type SectionDataComponentProps = {
      onDataChanged?: () => void, // call this whenever the data updates.
    }
    
    export class SectionDataComponent<P : SectionDataComponentProps, S, ItemT> extends React.PureComponent<P, S> {
    
      // Implemented by subclasses
      getSectionData() : Array<SectionT<ItemT>> { 
          // returns an array of sections for a SectionList...
      }
      render() {
        // business logic component only.
        return null;
      }
    }
    

    The parent component keeps track of them through the use of ref, and then calls getSectionData() as needed.