How To Optimize The Performance Of React Native App?
CONTACT

Best Guide To Optimize React Native Performance In 2021

Omji Mehrotra By Omji Mehrotra | July 14, 2021
best guide to optimize react native performance

Even after hours of coding a React Native app, programmers are likely to face performance issues as a result of using this cross-platform technology. Disappointed? It’s quite obvious that you don’t expect to identify such sorts of lags or glitches after dedicating your crucial time & giving your best efforts to any mobile app development project. But there is nothing unusual if your React Native app’s performance is not up to mark as you’re not the only horse facing such hurdles. 

The stunning USPs of react native may compel you to leverage this cross-platform technology but are you prepared to face challenges associated with it? 

some notable react native challenges for developers

You will be amazed to know that there are certain performance-related issues that will surely force you to get a guide on how to improve react native app performance as the need of the hour. Take a chill pill as this article is all about the tips to speed up your app with a list of react native best practices 2021. 

Tips To Boost React Native App Performance Successfully 

Now fold your sleeves to improve React Native app performance by trying these tested tactics by expert programmers:

#1- Replace ScrollView with SectionList or FlatList to Render long lists  

There is a probability of getting react native performance issues if you have got a long list of items to render all at once. You have two major options to render a huge list of components either in a scrollable format with ScrollView & in a listing format with FlatList.  

Implementing ScrollView is an ideal approach to display a list of finite items in a sophisticated manner. However, showcasing a host of items in a form of a scrollable list can slow down the overall performance of the React Native application. 

See how ScrollView format looks:

<ScrollView>

  {items.map(item => {

    return <Item key={item.name.toString()} />;

  })}

</ScrollView>

Considering such pre and post app launch snags to avoid, it’s advisable to choose FlatList over ScrollView to render all countable items with attributes of lazy loading that helps in improving the app’s performance. 

See how FlatList format looks:

<FlatList

  data={elements}

  keyExtractor={item => `${items.name}`}

  renderItem={({ item }) => <Item key={item.name.toString()} />}

/>

The major advantage of using FlatList is the portrayal of the selected items on the screen. It only displays the desired set of components & further eliminates them when they’re not supposed to be visible over the screen. The mobile app performance metrics mark this technique as a worthful strategy to conduct result-driven react native app optimization with benefits of low memory usage & high-performance speed.   

#2- Say No to passing Inline Functions as Props

Never follow the below command while passing any function inline as a component’s property:

function MakeBeverage(props) {

  return(

    <Button title=’ Make Beverage’ onPress={props.onPress}/>

  )

}

export default function BeverageMaker() {

  return (

    <View style={styles.container}>

      <MakeBeverage

        onPress={()=> console.log(‘making some beverage’)}

      />

    </View>

  );

}

In our guide to know how to improve react-native performance, we recommended programmers to avoid the above method as it recreates functions whenever a new reference gets rendered by the parent. It is clearly understood that child components get re-rendered automatically even if master props remain the same. As a part of key mobile app development strategies to deal with performance issues of an app, developers must define the function in a class format or within a function to eliminate the chances of re-renders. 

Here is the right command to passing functions while making changes in your cross-platform application. 

export default function BeverageMaker() {

  function handleMakeBeverage(){

    console.log(‘Making beverage, please wait!’)

  }

  return (

    <View style={styles.container}>

      <MakeBeverage

        onPress={handleMakeBeverage}

      />

    </View>

  );

}

#3- Eliminate Console Statements

When a developer aims to debug JavaScript codes, it becomes imperative to implement console statements for development purposes only. 

Also, read some tips for Javascript performance optimization 

Programmers must ensure that these console statements are removed before bundling as they can create some critical performance issues with React Native platform. If you don’t want such statements to mess with the Javascript thread, you must run a third-party react-native app optimization tool i.e babel-plugin-transform-remove-console which is a preferred plugin to remove console statements. You can simply use the following commands to install this plugin:

npm install babel-plugin-transform-remove-console

#  

OR

yarn add babel-plugin-transform-remove-console

Once you’re done with plugin installation, make the required changes to the .babelrc file to eliminate console statements as shown below:

{post-app

  “env”: {

    “production”: {

      “plugins”: [“transform-remove-console”]

    }

  }

}

#4- Do consider using the RAM format 

In iOS app development, the role of RAM format comes up with a single indexed file that will be loaded by React Native for a single module at a time. However, while using tools for Android app development, implementing the same RAM format will let you create a set of files for every particular module by default. 

Furthermore, you can also create a single file in Android app development in the same way you did in iOS unless you don’t desire to consider using multiple files at less memory & high efficiency with Android.

As React Native best practices for 2021, we encourage coders to simply get started with the RAM format in Xcode to tackle the performance issues with apps. Edit the build phase with a “bundle command for React Native code & images earlier to ../node_modules/react-native/scripts/react-native-xcode.sh & add export BUNDLE_COMMAND=”ram-bundle” to it. The next step goes as follows:

export BUNDLE_COMMAND=”ram-bundle”

export NODE_BINARY=node

../node_modules/react-native/scripts/react-native-xcode.sh

In Android app development, you can start editing your android/app/build.gradle file. Continue the line with apply from: “../../node_modules/react-native/react.gradle” or add the project.ext.react block with the following command:

project.ext.react = [

  bundleCommand: “ram-bundle”,


Write these lines of codes to create a single indexed file on Android: 

project.ext.react = [

  bundleCommand: “ram-bundle”,

  extraPackagerArgs: [“–indexed-ram-bundle”]

]

#5- Avoid Expensive & Unreasonable Renders 

To restrict unreasonable re-rendering, React came up with memo HOC (High Order Component) in its React 16.6 update. Later on, it introduced the useMemo hook in React 16.8 update for productive optimization of expensive renders. 

One can also perform similar actions with help of useCallback hook that slightly differs from useMemo. useCallback reverts a memoized callback while useMemo returns a memoized value.  Here is how useCallback hook & useMemo are used to cope with reach native performance issues:

a) The useMemo hook:

import React, {useMemo} from ‘react’

import {FlatList} from ‘react-native’

import data from ‘./data’

const App = () =>{

    const rateCompare = 3;

    const computedValue = useMemo(() => {

        //supposed computationally intensive calculation

        const result = data.filter((d) => d.rating > rateCompare);

        return result;

    }, [rateCompare]);

      const renderItem = ({ item }) => (

          <View>

            <Text>{item.state}</Text>

          </View>

      );

    return (

        <FlatList

          data={computedValue}

          renderItem={renderItem}

          keyExtractor={item => item.id}

        />

    )

}

b) The useCallback hook:

import React, {useState, useEffect, useCallback} from ‘react’

import {FlatList} from ‘react-native’

import data from ‘./data’

const App = () =>{

    const [values, setValues] = useState([]);

    const rateCompare = 3;

    const valuesCallback = useCallback(() => {

        //supposed computationally intensive calculation

        const result = data.filter((d) => d.rating > rateCompare);

        setValues(result);

    }, [rateCompare, setValues]);

    useEffect(() => {

        valuesCallback();

    }, [valuesCallback]);

    const renderItem = ({ item }) => (

        <View>

          <Text>{item.state}</Text>

        </View>

    );

    return (

        <FlatList

          data={values}

          renderItem={renderItem}

          keyExtractor={item => item.id}

        />

    )

}

Let’s make you familiar with react.memo, also referred to as HOC i.e High Order Component. 

While keeping local databases for react native app development in mind, React.memo() appears for memoization. In simple words, in case of any component getting the same set of properties simultaneously, it will go ahead with previously cached properties to further bring a JSX view that has been achieved by the functional component once. In this way, react.memo contributes to react native app optimization at reduced rendering costs to develop iOS app & Android app for a business. 

Also read the pros of a custom mobile app for business

Now it is necessary to highlight this point that memo must be used when it is required. It is not mandatory to involve memo in our guide on how to improve react native performance as there is a slight chance that there will be no performance issues due to re-rendering. Check out these commands on memo to get some idea:

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>

  ) 

}

Both useMemo & useCallback can optimize a specific process while react.memo can entirely optimize a component. However, it is suggested to use them only if you’ve found certain issues with react native performance monitoring.  

#6- Image Size Adjustments (Resizing & Scaling)

Images can also impact the performance of a react native app. They can bring some significant lags in the speed of PWAs or platforms built on web application architecture but modern browsers are capable of handling such issues relating to images with great support for fast downloading & scaling. 

react native in image resize mode

If a react native app is loaded with a bundle of images with high-quality graphics & content, it’s more likely to suffer too many performance lags due to memory overuse. To avoid facing app crashes or laggy performance, the UI UX design team must ensure that each image is optimized to match the resolution & size requirements for every device. You can effortlessly make the right image size adjustments in cross-platform app development with react native by:

  • Using images in PNG format, not in JPG
  • Rendering images in WEBP format to reduce their binary size for react native development for iOS & Android up to a greater extent. 
  • Loading images of small resolution in the app

#7- Do Cache all Images Locally

Heading to the next section in our guide on how to improve react native performance, let us unveil a useful trick to resolve image issues i.e ‘image caching’. 

Caching is a way to deal with image problems that further optimizes the overall performance of your react native application. However, you need to save the images locally while caching them at the time of loading in your app. 

By caching images locally in the subsequent requests, you will not only improve the app’s performance but also save a couple of minutes in loading images. Now it’s the right moment to recall the debate on cross-platform vs native app development for iOS & Android as here caching with the image component is meant for iOS only, not for Android. 

Read how ios app benefit business to grow

Here is a way to do local image caching:

<Image

  source={{

    uri: ‘https://unsplash.it/200/200?image=8’

    cache: ‘only-if-cached’

  }}

  style={{ … }}

/>

Although React Native is quite particular about image components, it still lacks some significant solutions to diminish the impact of the following issues identified by a react native performance testing tool:

  • Image flickering & cache misses
  • Attaching multiple images on a single screen
  • Low app performance 
  • Reduced image loading speed
  • Poor cache performance, & more

As discussed previously, one must consider using a fast loading image format with some preferred react native libraries with such remarkable cross platform app development frameworks

Also consider reading our top Android libraries list here

#8- Remove Nonessential Libraries & Add-ons

lets know about react native library errors

If you’re lacking time to go through an essential backend development tutorial for react native performance optimization then this tip will help you in catching the bull’s eye. 

Let us come to the point as we are here to talk about the role of a library in the performance of a react native application. The entire functionality of a react native app reflects the key features of the library used for its development. Hence, you’ve to be selective about the no. of libraries & features you desire to integrate with your app. 

Remove unnecessary or irrelevant libraries & dependencies at priority. Try to reduce nonessential navigations, animations, sections, or other functions that will increase screen loading time to worsen app performance. 

#9- Run Nativedriver for Animation

What’s the most efficient method to import animated elements in react native apps? Most programmers prefer to run animations in a JavaScript thread that further descends down their loading speed on the app. JS thread gets blocked when used for rendering animations & hence, doing so is not advisable as a part of react native app development strategy

It’s possible to give a native modification to animations before you start running animations with the support of animation APIs that can be serialized. So, all you need to do is to use native codes to run the animations on the UI thread so that you don’t have to worry about animations even if Javascript threads get blocked resulting in react native android slow performance. 

Here are some nativedriver configurations for animation APIs: 

import React, {useRef} from ‘react’

import {Animated} from ‘react-native’

const App = () =>{

  const opacity = useRef(new Animated.value(0)).current

  const showVal = () =>{

    Animated.timing(opacity, {

      toValue: 1,

      duration: 500,

      useNativeDriver: true,

    }).start();

  } 

  …

  return (

    <View>

        <Animated.View>

          <Animated.Text>Text to show</Animated.Text>

        </Animated.View>

        <Button title=”Show” onPress={showVal} />

    </View>

  )

}

#10- Never overuse High-order Elements

If you want to dig into the facts on how to improve react-native performance then you deserve to know that using higher-order elements would be favorable to put similar patterns with your components. It doesn’t matter if your app is basic or complex, you can compile such components to improve the quality of your code not only with react-native but also with different ide and tools for golang development.  

Some programmers may find this method inappropriate for improving the performance of a react native app but it doesn’t matter if outcomes are the same as expected. However, one should be careful while introducing these high-order elements specifically when the rendering method is applied. 

React Native is incapable of differentiating identical components that retards the performance of reconciliation algorithms. In addition to this, it also demands React Native to implement practices to shorten the mobile app development lifecycle.  

#11- Using Hermes 

Using Herpes is a part of every guide on how to improve react native performance in 2021. This JavaScript engine made its first-ever appearance in 2019 under the banners of Facebook. Hermes emerged as a powerful technology to boost app performance without compromising the memory consumption, app size, & overall app response time.

Grab some tips to increase mobile app response rate 

Hermes is not available in React Native by default. But there is no hard & fast rule to use in your app. Simply enable it to get started with Hermes in react native app development. Hermes was only meant to be used with iOS app development tools till the day its upgraded version was released right after the launch of React Native 0.64. 

To get started with Hermes for react native app optimization, you have to upgrade the previous version of this mobile app development framework to the latest one. If you’re intending to use Hermes to build a native Android application then you’ve to modify your android/app/build.gradle with these commands:

 project.ext.react = [

      entryFile: “index.js”,

      enableHermes: true

  ]

You can also perform it in this way:

def enableHermes = project.ext.react.get(“enableHermes”, true);

While using ProGuard, you’re required to open your proguard-rules.pro & go ahead with the below-give rules:

-keep class com.facebook.hermes.unicode.** { *; }

-keep class com.facebook.jni.** { *; }

Now the next step is to clean & recreate your app if you’ve already done it earlier. You just have to run cd android & continue with a ./gradlew clean command.  

Note: Always ensure that you’ve updated build.gradle file as per the latest Gradle releases while upgrading your existing React Native to the current version. 

It will be interesting to know that the recent version update of Hermes for iOS rolled out in React Native 0.64 on March 12, 2021. 

Also read top swift iOS app development business benefits 

To get started with Hermes on your cross-platform app development project for iOS, you need to follow a configuration i.e hermes_enabled to true & define pod install in Podfile

use_react_native!(

   :path => config[:reactNativePath],

   :hermes_enabled => true

)

How Does A React Native Application Perform?

how to create react native app architecture

Using a high-performance framework like React Native is a superlative approach to build cross-platform apps with ultra speed & proficiency. Being desirous to experiment with this ground-breaking technology, more & more tech talents are compelled to adopt the new digital transformation trends inspired by this preeminent framework for on-demand app development for all platforms.

We can say that it’s no more a tedious task to deliver out-of-box mobility solutions for universal platforms as React Native takes a lead to make it effortless for modern developers. And when it comes to our guide on how to improve react native performance in 2021, we’ve discussed plentiful tips to do so. 

Before getting closure for this discussion, you must grab a short overview of the core components of React Native architecture to understand how apps powered by this framework work. For your general information, react native apps run on three threads as listed below:

#1- The Main UI Thread:

The main thread is concerned about the way an app’s UI interacts with users. It’s all about how the components in the user interface respond to the gesture made by the other end-user.

#2- JavaScript Thread:

React native declares JavaScript code in a particular JS engine after each action done on the app. It is responsible for the response of UI on every action.  

#3- The Shadow Tree Thread:

Third thread takes a count on the layouts on the JavaScript. Afterward, it renders a view by delivering the same information to the native side of the app. 

React Native apps compiles a series of native components that are based on top programming languages including JavaScript, Objective-C, & Swift. Note that the React Native framework is built on JavaScript & it takes care of scripts. 

Hire Appventurez for World-class React Native Solutions

Once you delve into the dominion of cross-platform technologies, you can’t resist the splendor of React Native in delivering high-performing mobility solutions with smart features. After all, this amazing cross-platform framework holds a wider user base for its incredible superiority in creating stellar mobile apps for universal platforms. If you want to grab some insights on how app development with react native can reduce cost, you must get familiar with the caliber of this framework in improving the developer’s productivity with reduced usage of resources & time. 

However, our guide on how to improve react native performance is credible to bring you here to investigate more about the ins & outs of cross-platform mobile app development for startups. So, if you’ve got any app ideas in your mind, don’t hesitate to bring them to Appventurez, an award-winning group of tech nerds who’re always excited to shape innovations with ground-breaking mobile app solutions for diverse business verticals & industries. Stay tuned for more tech-based articles to know more about our techniques & methodologies on popular mobile app trends!!

Omji Mehrotra
Omji Mehrotra

Co-Founder and AVP Technology at Appventurez. An accomplished Android and React Native developer who is a fan of clean and optimized code, he is a passionate team builder having smart project managerial skills and has a deep love to provide end to end solution.

⚡️ by Appventurez

Leave a Reply

Please rate*

Your email address will not be published.

Hey there! This is Omji, author of this blog. Leave your email address and we'll keep you posted on what we're up to.

This will subscribe you to Appventurez once-a-month newsletter. You can unsubscribe anytime. And we promise not to pester you or share your data :)

Hey there, wondering where this article came from? It was produced by some people at Appventurez, a Mobile & Web App Development Company. We are here for solutioning of your technological needs.

Our Latest Blog

shape your ecommerce with augmented reality just like gucci
GUCCI's AR Sneakers: How You Can Also Shape Your Ecommerce With Augmented Reality?

In the competitive tech world, retail firms & eCommerce business owners are...

Read more
why is it the right time to invest in ott app development
Why Is It The Right Time To Invest In OTT App Development?

Over 70% of the US residents are active subscribers to at least one popular OTT...

Read more
How Buy Now Pay Later Apps Are Expanding Their Coverage In The US Market?

In the financial sector, buy now pay later(BNPL) has become a hot topic. In Jan...

Read more

We’re your neighbor

Appventurez is a well known mobile app development company in the USA and India that works to build strong, long-lasting relations with its clients in different locations.

india flag appventurez
India (HQ)

Logix Infotech Park, 1st Floor, Plot No. D-5, Sector 59, Noida, Uttar Pradesh 201301

Inquiries : +91-9899 650980

5 Taunton Place Craigieburn VIC Australia

Inquiries : +1-815-283-8355

Office #216 Regus Tower Bank Street, Doha Qatar

Inquiries : +974-33497259

usa flag appventurez
USA

12501 W Chandler Blvd, Suite 200 Valley Village, CA 91607 USA

Inquiries : +1-888-822-1022

Rimal 5 Jumeirah Beach Residence 2 Dubai

Inquiries : +1-815-283-8355

south africa flag appventurez
South Africa

3 monterrey Complex, 63 Montrose Avenue, Northgate, Johannesburg, 2191

Inquiries : +27 737 810 945

7 Hanover House, Chapel Street, Bradford BD1 5DQ, United Kingdom

Inquiries : +1-815-283-8355

Netherlands flag appventurez
Netherlands

Amstelveen, Netherlands

Inquiries : +31-(0)-61-020-9692

Calle Ambar 2711, Av Victoria, 45089, Zapopan, Jalisco, Mexico

Inquiries : +521 332 393 9998

ghana flag appventurez
Ghana

North Industrial Area, Otublohum Road, Opposite Melcom Plus, Accra, Ghana

Inquiries : +27 737 810 945

appventurez worldwide presence
india flag appventurez
India (HQ)

Logix Infotech Park, 1st Floor, Plot No. D-5, Sector 59, Noida, Uttar Pradesh 201301

Inquiries : +91-9899 650980

5 Taunton Place Craigieburn VIC Australia

Inquiries : +1-815-283-8355

Office #216 Regus Tower Bank Street, Doha Qatar

Inquiries : +974-33497259

usa flag appventurez
USA

12501 W Chandler Blvd, Suite 200 Valley Village, CA 91607 USA

Inquiries : +1-888-822-1022

Rimal 5 Jumeirah Beach Residence 2 Dubai

Inquiries : +1-815-283-8355

south africa flag appventurez
South Africa

3 monterrey Complex, 63 Montrose Avenue, Northgate, Johannesburg, 2191

Inquiries : +27 737 810 945

7 Hanover House, Chapel Street, Bradford BD1 5DQ, United Kingdom

Inquiries : +1-815-283-8355

Netherlands flag appventurez
Netherlands

Amstelveen, Netherlands

Inquiries : +31-(0)-61-020-9692

Calle Ambar 2711, Av Victoria, 45089, Zapopan, Jalisco, Mexico

Inquiries : +521 332 393 9998

ghana flag appventurez
Ghana

North Industrial Area, Otublohum Road, Opposite Melcom Plus, Accra, Ghana

Inquiries : +27 737 810 945

10 Global Offices

Across 124 territories and 33.6k global workspace

700+ Worldwide clients

Largest International clients

24 x 7 Availability

Effective support, anytime