0

In my current use-case, I'm adding items to a ScrollView. I noticed that if I add an item to the items collection located in state, all the items re-render.

Is there any workaround I can do? The current implementation has to be ScrollView, so changing to FlatList or any other implementation of List would be irrelevant.

<View style={{flex: 1}}>
    <ScrollView>
      <TouchableWithoutFeedback accessible={false}>
        <View style={{flexDirection: 'column', alignItems: 'center'}}>
        {this.state.items.map(( item, key ) =>
        (
          <Flag country={item} key={key} />
        ))}
        </View>
      </TouchableWithoutFeedback>
    </ScrollView>
  </View>

Thank you

Amaros
  • 503
  • 5
  • 20

3 Answers3

1

If your items be PureComponent they won't render again when you add a new item to the list unless their props has been changed ... or you can implement the shouldComponentUpdate method in a regular Component and specify when this component should render again.

Code:

ScrollView:

<ScrollView>
    {data.map(item =>
        <ScrollViewItem itemInfo={item} />
    )}
</ScrollView>

ScrollViewItem with PureComponent:

class ScrollViewItem extends React.PureComponent {
    ...
    render() {
        ...
    }
}

ScrollViewItem with shouldComponentUpdate:

class ScrollViewItem extends React.Component {

    shouldComponentUpdate({ itemInfo }) {
        if(itemInfo.id != this.props.itemInfo) {
            return true;//this component will update
        }

        return false;//this component won't update 
    }
    ...
    render() {
        ...
    }
}
ehsaneha
  • 1,665
  • 13
  • 8
0

I would check into using FlatList instead of using a map from a set of states to render a ScrollView. Essentially, once you update this.state.items, you call for a rerender of anything involved with that state.

I've used this resource and it should help you upgrade your code:

http://matthewsessions.com/2017/05/15/optimizing-list-render-performance.html

ReyHaynes
  • 2,932
  • 1
  • 15
  • 22
  • I am aware of FlatList, but as I mentioned it has to be a ScrollView, is there any way I can add an item without re-rendering all the items in the ScrollView? – Amaros Nov 16 '17 at 17:11
  • Sorry. I actually meant using "the concept" of FlatList instead of using FlatList . In other words, look into creating recyclable child views. – ReyHaynes Nov 16 '17 at 17:27
0

In my case, setting flexShrik: 0 to all elements inside scroll view, fixed the problem.

Hayyaun
  • 303
  • 3
  • 10