mercredi 16 juin 2021

React Native FlatList with customizable props (good practices)

This question is about good practices and patterns when generalizing components.

I am implementing a FlatList wrapper component "UserList", which renders "UserListItem".

My idea is to make it flexible, allowing passing custom props like "keyExtractor" or "renderItem" as optional props. If the props are not passed, then the list will use its own methods.

So, I have the following:

const UserList = memo(
  (props) => {
     const {
        data,
        keyExtractor,
        listKey,
        ListEmptyComponent,
        initialNumToRender,
        onRefresh,
        onEndReached,
     } = props;


     const _keyExtractor = useCallback((...) => ..., []);

     const _renderItem = useCallback((...) => ..., []);

     ...

     return (
        <FlatList
           ...
           keyExtractor={keyExtractor || _keyExtractor}
           renderItem={renderItem || _renderItem} 
           ...
           // some default configurations (updateCellsBatchingPeriod, windowSize, ...) for this type of component
        />    
  }
  (prevProps, nextProps) => { 
     ...
  }
);

Is there any difference between implementing the list as I did and using defaultProps for defining the default keyExtractor and renderItem?

I mean, something like this:

UserList.defaultProps = {
  keyExtractor = (...) => ...,
  renderItem = (...) => ...
};

avoiding the definition inside the component.

Also, do you consider making reusable FlatLists wrappers components a good practice?

Could it be more professional and easier to read making another FlatList wrapper component that have its own renderItem and keyExtractor (avoiding the generalization of my current UserList component)?

Aucun commentaire:

Enregistrer un commentaire