Tips on Optimizing React Native Performance
Put console.logs in your render statements and figure out just how often things are getting rendered. You can get away with a lot for a while using react.
- Use PureComponent to avoid wasteful re render
- Avoiding re-rendering of components, We can signal React not to render in a couple of ways:
- Returning the same element reference (use the memoize function from lodash if you don’t want to implement the caching yourself.)
- Returning false from shouldComponentUpdate
- Attach a key associated with your object for ListViews . This will avoid unnecessary re renders on list update
For Example :
What happens when we sort, for instance, “users” array or add/remove a new user object to the array from the middle?
It will destroy rest User components and will create new components. But is there any need to do that? NO! Reconciler can’t find a way how to reuse existing components and that’s why it recreates many User components. It will send data to shadow thread through RN bridge – yoga will calculate much data again, and will send to UI, and it will render UI. To avoid similar performance issue – think what key are you give to your component? Is it attached to your data or not. So if you’ll give <User /> component user.id as key, it will reuse existing components, and just will move they directions, instead of destroying and creating, this will improve your list performance a lot.
So we can re rewrite the function,
- Get rid of ListView
- FlatList – More performant compared to ListView. ListView rendering can get slow once the number of items grows larger. FlatList significantly improves memory usage and efficiency (especially for large or complex lists) while also significantly simplifying the props — no more dataSource necessary!
Optimizing Redux (gain up to 10x speed)
- When using redux, we use the higher-order component connect(). This component retrieves the store for the context and calls mapStateToProps when the state changes. An example is shown below.
But if mapStateToProps function performs some calculation, it can cause connect() to re-render unnecessarily.
- We can gain faster update speeds on redux store by properly designing the redux store state. Use normalizr library to flatten nested structure from api
- Refer official react redux api documentation for details : https://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html