Photo by Sanjeevan SatheesKumar on Unsplash
Recently my team have started working on the first big React Native app. Quite soon I had to implement a page with filters list:
In the initial version of the page, a single click on checkbox element initiated a noticeable delay.
FlatList[update] takes most of 250ms
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 ApproachTo 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
:
After the small change, render time went down to 56ms.
To cut down render time 5x times, I had to stop mutating data source for FlatList and rerender items ONLY if they have changed.
categories
array to map over. And calculate isShown
on theFlatList
level. Now the data source is always the same object and isShown
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.
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.
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!
ProductCrafters/rn_perf_Contribute to ProductCrafters/rn_perf development by creating an account on GitHub._github.com
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 ✉️ [email protected]