How We Improved React Native List Performance by 5X
Recently my team have started working on the first big React Native app. Quite soon I had to implement a page with filters list:
Problem
In the initial version of the page, a single click on checkbox element initiated a noticeable delay.
There are 75 elements in the list and only 11 visible at a single moment of time. So I was expecting FlatList (which has a virtualization feature out of the box) to rerender only a single changed element (in the worst case — only visible elements). But it rerenders all items.
Original Approach
To show a selectable list of categories I retrieve Categories
from redux state and create a new array extendedCategories
that contains Category data and flag isShown
:
Solution
To cut down render time 5x times, I had to stop mutating data source for FlatList and rerender items ONLY if they have changed.
- Instead of creating a new data source object after each rerender, I use existing
categories
array to map over. And calculateisShown
on theFlatList
level. Now the data source is always the same object andisShown
prop will get new value only when checkbox changes it’s value.
2. Use PureComponent
for renderItem
PureComponent
is similar toComponent
. The difference between them is thatComponent
doesn’t implementshouldComponentUpdate()
, butPureComponent
implements it with a shallow prop and state comparison.PureComponent
’sshouldComponentUpdate()
only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences.
Redux State
Categories
— an array of all meta info about categoriesSelectedCategories
— an array with only selected categories {id, name}
After clicking on the category, it is added to SelectedCategories
array, and Categories
object is always the same, without mutations. If the user clicks on an already selected category, it is being removed from the SelectedCategories
array.
Profiling
From my experience, unlike React, extra rerender in React Native affects user experience much worse. The fastest way to find extra renders is old console.log
in render function. After you found an issue, use Chrome Profiler tab in developer tools to dig into it. Or new React Profiler (coming in 16.5).
Want to play with the code? Check out the GitHub repo!
P.S. If you enjoyed this article and want more like these, please clap and share with friends that may need it.
🚀 My team uses JS and React to build production apps over 3 years. We help US startup founders to bring their ideas to life. If you need some help, send a message ✉️ oleg@productcrafters.io