What am I doing ?
Trying to render a FlatList based on some items stored in state.data
. A button is present which upon press appends a new item in state.data
.
What is the problem ?
Upon pressing the button, I'm expecting that the renderItem to be called only state.data.length
number of times whereas it's being called 2*state.data.length
number of times. Also, this 2x behaviour is not always consistent and changes as state.data.length
increases.
Ex: when state.data.length=3
, then on initial render, number of times renderItem is called exactly 3 times which is same as the number of items in state.data
and upon pressing button which appends a new item to state.data
and now state.data.length=4
and renderItem is called 8 times i.e. 2*state.data.length
times.
But, when state.data.length=11
, then on initial render, renderItem is called exactly 21 times and upon pressing button which appends a new item to state.data
and now state.data.length=12
and renderItem is called 23 times times which deviates from 2*state.data.length
behaviour.
What am I expecting ?
renderItem to be called only state.data.length
number of times on initial and subsequent renderings.
What I've tried ?
- Created a new project from scratch to test this behaviour with no luck.
- Made component inside renderItem PureComponent. Still the same behaviour as mentioned.
- Made a CodeSandbox at https://codesandbox.io/s/react-native-nn73t with react-native-web with the same behaviour as before. Please refer this sandbox for the code.
- Using props such as maxToRenderPerBatch, initialNumsToRender etc but to no avail either. Though using them with relatively large
state.data
does bring down the number of times renderItem is called but it's still not that great decrease. - Referred similar questions but couldn't get much clarity
The real issue I'm facing is when I'm trying to render chat messages (fetching through API call and setting it inside the state) inside a FlatList. Right now there are about ~200 messages for which the renderItem is being called in a range of 800-1200 times which is taking a hit on the performance.
Is this behaviour which is deviating from my expectation expected ? If yes, then what's the logic behind this. If no, then what am I doing wrong here ?