How to improve the performance of a React Native App?

Avoid Using Scroll View to Render Huge Lists

When it comes to displaying items in React Native with scrollable lists, there are two ways to do it using ScrollView and FlatList components. Displaying a scrollable list by using ScrollView is simple, but on the other hand, it can directly affect the overall performance of the React Native app. This is especially true when there are a large number of items in the list. To fix this issue, experts recommend listing the items with FlatList.

Avoid Passing Functions Inline as Props

When it comes to passing a function as a property to a component, it is better to avoid passing that function inline. At times when the parent re-renders a new reference, which creates another function. Simply put, the child component re-renders even when the props did not change at all. But, there is a solution. Best practices recommend you declare the function as a class method or as a function inside a functional component. In this way, you can remove any possibility of removing references across re-renders.

Go for Resizing & Scaling Images

Make sure you focus on optimizing images, including graphical content when improving the performance of your React Native app. When you render multiple images in your React Native app, it may lead to high memory usage on a device. Here comes the importance of optimizing images appropriately in terms of resolution and size. If not properly done, your app is likely to crash due to memory overload. Some best React Native app image practices include using PNG format instead of JPG format and smaller-resolution images. You may also utilize the WEBP format to reduce the binary size of your images on iOS and Android by almost a third of the original size.

Avoid Unnecessary Renders

When it comes to avoiding unnecessary renders on the main thread of React Native apps, there is an effective optimization technique. You can do it simply by using React .memo() which can handle memoization. Simply put, when a component receives the same set of properties more than once, it will use the previously cached properties and render the JSX view returned by the functional component only once. This reduces overall rendering overhead

Use FlatList or SectionList to render large lists in React Native

If you have a large list, rendering all the items at once can cause a performance issue, but lazy loading with FlatList can improve performance.

The FlatList component renders only the items that will be displayed on the screen and removes them when they are no longer displayed. This saves a lot of memory, making the app much faster:

import React from "react";
import { FlatList } from "react-native";
const data = [
  {
    id: 1,
    text: "First",
  },
  {
    id: 2,
    text: "Second",
  },
];
const App = () => {
  const renderItem = ({ item }) => (
    <View>
      <Text>{item.text}</Text>
    </View>
  );
  return (
    <FlatList
      data={data}
      renderItem={renderItem}
      keyExtractor={(item) => item.id}
    />
  );
};

FlatList and SectionList serve similar purposes. Both can improve the performance of your app. However, SectionList is more suitable when rendering sections. Virtualized List may also be used if you need more flexibility.

It is also possible to render lists with ListView and, while this can be used for small lists, it is not recommended for large lists. Although it is possible to render lists with a map, it is not advisable to do so in React Native.

Remove all console statements

Console statements are necessary for debugging JavaScript codes, but they are only meant for development purposes. These statements could cause serious performance issues in your React Native application if they are not removed before bundling.

While you could install plugins such as babel-plugin-transform-remove-console to remove these statements from production, it is better to manually remove them if you don’t want to add additional dependencies to your app.

Memoize expensive computations

React introduced the memo HOC (Higher Order Component) in React v16.6 for preventing unnecessary re-rendering and the useMemo hook in React v16.8 for optimizing expensive computations.

However, it is also possible to use the useCallback hook to do that. The major difference between useMemo and useCallback is that useMemo returns a memoized value, but useCallback returns a memoized callback.

Let’s take a look at each of them.

The React.memo Higher Order Component (HOC)

React.memo was introduced to functional components to serve the same purpose that React PureComponents serve in class components. memo prevents unnecessary re-rendering of a component and can help to optimize an application.

However, like other optimization techniques, a memo should only be used when it is necessary. In some cases, unnecessary re-rendering will not impact performance much.

Here is an example to illustrate the memo:

import React from "react";
import { View, Text, TouchableOpacity } from "react-native";
const Element = ({ children, value, setValue }) => {
  const handleOperation = () => setValue(value * 2);
  return (
    <View>
      <Text>{value}</Text>
      <TouchableOpacity onPress={handleOperation}>{children}</TouchableOpacity>
    </View>
  );
};
export default Element;
import React, { useState } from "react";
import { View } from "react-native";
import Element from "./Element";
const App = () => {
  const [firstNum, setFirstNum] = useState(5);
  const [secondNum, setSecondNum] = useState(5);
  return (
    <View>
      <Element setValue={setFirstNum} value={firstNum}>
        {" "}
        Add First{" "}
      </Element>
      <Element setValue={setSecondNum} value={secondNum}>
        {" "}
        Add Second{" "}
      </Element>
    </View>
  );
};

The problem with the above code is that when any of the buttons are pressed, both buttons will re-render even though only the states for the pressed button will be changed.

This can be fixed by wrapping the Element component with the React.memo HOC. Here’s how to do that:

import React, { memo } from "react";
import { View, Text, TouchableOpacity } from "react-native";
const Element = ({ children, value, setValue }) => {
  const handleOperation = () => setValue(value * 2);
  return (
    <View>
      <Text>{value}</Text>
      <TouchableOpacity onPress={handleOperation}>{children}</TouchableOpacity>
    </View>
  );
};
export default memo(Element);

This would fix the re-rendering issue. However, it should be used only when the re-rendering is causing performance issues.

The useMemo hook

useMemo returns a memoized value of a function. However, it should only be used when performing expensive computations.

For instance, suppose we want to filter some data coming from our API by their rating. We could memoize the computation to recalculate the results only when the values change:

const data = [
{id: 1, state: 'Texas', rating: 4.5},
{id: 2, state: 'Hawaii', rating: 3},
{id: 3, state: 'Illinois', rating: 4},
{id: 4, state: 'Texas', rating: 5},
{id: 5, state: 'Ohio', rating: 4.5},
{id: 6, state: 'Louisiana', rating: 3},
{id: 7, state: 'Texas', rating: 2},
{id: 1000, state: 'Illinois', rating: 4.5},
]

If we wish to filter the data based on the rating (without memoization), we may use up a lot of memory.

For such, we don’t want to unnecessarily recalculate the values when other components re-render. We want to re-render or re-calculate only when the dependent rating changes.

Avoid Updating state or dispatch Actions in componentWillUpdate

You should make use of the componentWillUpdate lifecycle method to prepare for an update, not to trigger another one. If your aim is to set a state, you should do that using componentWillReceiveProps instead. To be on the safe side, use componentDidUpdate rather than componentWillReceiveProps to dispatch any Redux actions.

Avoid Excessive Use of Higher-Order Components

When your application becomes complex and you want to share common patterns across your components, it is common to use higher-order components. Using higher-order components is, in fact, a good practice, even if it can sometimes be arguable, as it increases indirection. However, it can increase the complexity of your code.

What you should really be careful about is not instantiating a higher-order component on the fly, specifically during a render method. This is because this pattern effectively creates new components on its own.

React Native does not know (and does not identify) that this is effectively the same component as before. This puts lots of pressure on the reconciliation algorithms. More than that, it also forces React Native to run all the lifecycle methods.

Latest

SENTRY integration in your React Native App for Error/Crash tracking

Sentry captures data by using an SDK within your...

Recall the concepts of useCallback.

useCallback hook is one of the best hooks offered...

Value of Comments in the code!!

During my journey of Software Development, I am always...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million...

Featured

Developing Enterprise Application in Node.js – CJS Vs ESM

Node.js is a popular runtime environment for building server-side...

Integrating your web react applications with their React Native(android and IOS) apps using QR code

Integrating a web application with Android and iOS apps...

YOLO: Bullet Paced Algorithm – popular choice for object detection in autonomous vehicles 

According to world health organization, more than 1.35 million...

Deep Linking with Firebase-Dynamic Links in React Native

Deep linking improves user engagement and provides a better user experience In today's era where everything is connected and we share links more often than...

Cashfree SDK integration in React Native App

Hello Everyone In this article we will learn how to integrate Cashfree payments SDK in React Native Application. The React Native Cashfree SDK  Cashfree provides a dedicated...

What is a Pure Component?

Imagine you are building a toy car out of Legos. The toy car has different parts, like wheels, a body, and a steering wheel....

LEAVE A REPLY

Please enter your comment!
Please enter your name here