React Native Developer

Monday, May 30, 2022

How to Get Better Performance Out of Your React Native App

How to Get Better Performance Out of Your React Native App





Received the planet over by staggeringly effective corporations like Facebook, Shopify, Coinbase, Tesla, and Friction, Respond native offers a promising arrangement for those searching for a sensible system on that to form cross-platform applications. Why area unit a number of of the world's biggest corporations creating the switch to reply Local?


It offers additional succinct and easier-to-understand code that may be shared across multiple platforms.

It offers quick iteration while not a compile cycle.
You can ship quicker and specialise in details that actually matter, creating your app look and feel fantastic.

To reach truth performance potential of your React Native app tho', improvement could be a crucial step. during this article, we tend to break down some optimizations that may create your React Native app double as quick and far more economical.



Improve Start-up Time

App start-up time means the time from app launch to draw content from the app. Decreasing bundle size and memory usage will help to improve the start-up time. We can enhance app performance by improving start-up time.

Hermes

Hermes is associate ASCII text file JavaScript engine optimized for RN. we are able to use Hermes to reinforce the start-up time as sanctionative it'll lead to minimized memory usage and a smaller app size. invariably check that to use the newest version of RN once victimisation Herms.

Enabling Hermes for Android

For Android applications, add following lines to android/app/build.gradle to enable Herms for Android.

project.ext.react = [
       entryFile   : "index.js",
   -   enableHermes: false  // clean and rebuild if changing
   +   enableHermes: true  // clean and rebuild if changing
]

If you're using ProGuard, add these rules in proguard-rules.pro:

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

Next, clean the build:

cd android && ./gradlew clean

Deploy the app

npm react-native run-android

Enabling Hermes for iOS

For iOS applications, add the following code block to ios/Podfile file to enable Herms for iOS.

use_react_native!(
   :path => config[:reactNativePath],
   # to enable hermes on iOS, change `false` to `true` and then install pods
-   :hermes_enabled => false
+   :hermes_enabled => true
)

Install the Hermes pod

cd ios && pod install

Deploy the app

npm react-native run-ios

useMemo

We can use useMemo hooks to avoid re-rendering, and it helps to stop re-rendering of kid parts by returning memorized values of a perform. If any element receives a similar props quite once, useMemo can use antecedently cached props and render the JSX read and come back the element. Thus, useMemo helps to enhance the performance of RN applications. However, it ought to be used only playing costly calculations, as ar able to} learn the computations to cipher the results if solely the values are modified.

We have used FlatList and Button within the below example. At the primary time, FlatList can render utterly, and once the user clicks the button count, it'll increase by one. Then the state is updated, and also the whole element can re-render with none amendment within the array. As in code, we tend to avoid this by wrapping FlatListItem (UseMemoFlatListItem) with useMemo. it'll check whether or not there area unit any changes in props and render the JSX given that there area unit changes. Otherwise, it'll come back the previous props and render the previous read.



import * as React from 'react';
import {View, FlatList} from 'react-native';
import {useState} from 'react';
import UseMemoListItemSeprator from './UseMemoListItemSeprator';

const data = [
   { name: 'Sri Lanka' },
   { name: 'India' },
   { name: 'Australia' },
];
const [arrCountry, setArrCountry] = useState(data);
const [count, setCount] = useState(0);

function UseMemoFlatListItem({item, onChange, arrCountry}) {
   return useMemo(() => {
       return (
           <View style={Styles.container}><Text>{item.name}</Text></View>
       );
   }, [item.status]);
}
return (
   <View style={Styles.container}><Button title='Increment' onPress={() => setCount(count + 1)} /><FlatList
           data={arrCountry}
           keyExtractor={(item) => String(item.name)}
           renderItem={({item, index}) => (
               <UseMemoFlatListItem
                   item={item}
               />
           )}
           ItemSeparatorComponent={() =><UseMemoListItemSeprator />}
           showsVerticalScrollIndicator={false}
       /></View>


Flipper


Flipper may be a debugging platform for golem, iOS, and RN apps. it's a layout and network inspector and shows logs with a clean UI. Flipper integrates directly with native code, thus it does not have a runtime distinction between JS engines or need remote debugging. we will track functions, methods, and lots of logical things by putting in the Flipper plugin, and it is put in directly from the desktop app.


Cache Images

RN provides an image as a core component that allows developers to display images. However, there are few issues with this image component. Some of them include rending many images on a single screen, image flickering, low performance in image loading, and cache loading. To solve these issues, we can cache the image and use the local cache in the subsequent request. However, RN supports built-in caching only for iOS and not for Android.

We can cache an image as shown below,

<Image
 source={{
   uri: 'https://unsplash.it/200/200?image=8',
   cache: 'only-if-cached'
 }}
 style={{ width: 400, height: 400 }}
/>

However, this method is not optimal, and still, there can be performance issues. However, these performance issues can be resolved using a third-party library called react-native-image, which supports both iOS and Android apps. The fast image allows users to render images quickly using a cache mechanism. Furthermore, it adds authorization headers and several other features.

import FastImage from 'react-native-fast-image'

const App = () => (
 <FastImage
       style={{ width: 400, height: 400 }}
       source={{
           uri: 'https://unsplash.it/200/200?image=8',
           headers: { Authorization: 'auth-token' },
           priority: FastImage.priority.normal,
       }}
       resizeMode={FastImage.resizeMode.contain}
   />
)

Additionally, we can use a library such as react-native-cached-image to cache and load images.

import { CachedImage } from 'react-native-cached-image';

<CachedImage
 style={{ width: 400, height: 400  }}
 source={{ uri: 'https://unsplash.it/200/200?image=8' }}
/>


It is essential to optimize your app images to improve the performance of the app. The best way to include images in your app is by saving them in appropriate formats, such as PNG or WebP. The WebP format, which was introduced by Google in 2010, is the most performant format among other formats.

Use NativeDriver with the Animated API


Developers are using animations in RN apps, and there are many ways to use animations in apps. However, running animations on the JavaScript thread is not a good practice. The best practice is to use an Animated library and the nativeDriver to push the details of the animation over the native bridge before it starts on the screen. We can use the nativeDriver with the Animated library by simply setting useNativeDriver as 'true.'

import React from 'react'
import {Animated} from 'react-native'

const App = () =>{

   Animated.timing(this.state.value, {
       toValue: 1,
       duration: 500,
       useNativeDriver: true,
   }).start();
   
}




2 comments:

  1. Very Informative and creative contents. This concept is a good way to enhance the knowledge. thanks for sharing.
    Continue to share your knowledge through articles like these, and keep posting more blogs.
    And more Information JavaScript Development Services

    ReplyDelete