Quick Summary:

This post will guide you through the best practices to improve your React Native app performance in 2022. The performance of web applications is a crucial factor, and speed plays a significant role in the success of an application. Let’s deep dive into discussing the approaches and strategies you require to speed up React Native performance.

Introduction

React Native has been growing by leaps and bounds since its inception in 2015, and it is believed that this cross-platform web app framework has overtaken the likes of Xamarin and Iconic.

React Native uses several ingenious approaches for DoM transactions, saving the time to refresh the UI. The decision-makers understand the criticality of having a dedicated React Native team in building a React Native app architecture. However, certain bottlenecks occur while scaling up the functionalities and operations, such as memory leaks in React Native.

Let’s get straight to analyzing the best ways for React Native performance optimization.

Improve React Native App Performance issues

To improve your React Native application performance, here are some common practices to follow, which will significantly benefit you in the long term.

Memory Leaks in React Native

Memory leakage

Memory leaks in React Native is one of the most common native applications, with many unnecessary processes running in the background.

With the use of Xcode, you can find React Native memory leak.

  • Go to XCode → Product → Profile (⌘ + I)
  • After that shows you, all templates choose leaks.

Also, through Android Studio, you can identify the memory leak in React Native

  • Run React Native app normally (react-native run-android)
  • Run Android Studio
  • On the menu, click Tools → Android → Enable ADB Integration
  • Click Tools → Android → Android Device Monitor
  • When Android Device Monitor shows up, click Monitor → Preferences

Perf Monitor is a good choice to address Android native memory leak.

Copy Text
Import PerfMonitor from 'react-native/Libraries/Performance/RCTRenderingPerf';
PerfMonitor.toggle();
 PerfMonitor.start();
 setTimeout(() => {
   PerfMonitor.stop();
 }, 20000);
}, 5000);

To fix the memory leak in React Native, you can use scrolling lists such as FlatList, SectionList, or VirtualList instead of Listview.

Scrolling list also helps in smoothing the infinite scroll pagination. If you’re building an application with a pull to refresh feature and large data points, it is advisable to consider it for React Native memory profiling.

Image Size Reduction

Image size reduction

Images are a big issue for high memory usage. React Native image optimization is essential for building a scalable app.

1. Use smaller-sized images.
2. Use PNG as opposed to JPG.
3. Convert your images to WebP format.

Why WebP Format?
WebP is the latest image format that delivers excellent lossless and lossy compression for web images. With WebP, webmasters and web developers can

  • WebP images can speed up your image loading time to 28%.
  • Reduced CodePush bundle size by 66% with .webp format
  • Helps to reduce iOS and Android binary sizes by 25% with . webp format
  • React NativeJS Thread feels so much faster
  • Navigator transitions are so much smoother

Cache the images locally

Image caching is important for loading images faster. As of now, React Native only provides image caching support on iOS. This is a quick example, as seen in the docs (IOS only)

Copy Text
< Image
  		source={{
    			uri: 'https://facebook.github.io/react/logo-og.png',
    			cache: 'only-if-cached',
 		 }}
 	 	style={{width: 400, height: 400}}
	/ >

For Android, there are some npm libraries available out there that helps to solve the image caching issue. Unfortunately, they don’t offer the best performance.

Avoiding Unnecessary Renders

Overriding a Component Update:
You should first ensure that your components require an updation and not pass too much needless work to Reconciler. This may probably drop your JS thread’s FPS. It might outspread from PureComponent instead of Component.

Copy Text
shouldComponentUpdate( nextProps, nextState ) { 
	if(nextProps.isUpdated == this.props.isUpdated) {
          return false; 
        } else {
	  return true; 
        }
  }

shouldComponentUpdate should always return a boolean  an answer to the question,

“should I re-render?”
Yes, it is advisable to have little component.

Using PureComponent for Improving React Native Performance

PureComponent in React doesn’t have a state; they just render your component based on the data passed via props. It re-renders only when the props change.

shouldComponentUpdate life-cycle method is used in regular non-pure React Component to cancel the re-render by returning false in certain scenarios.

Copy Text
class MyPureComponent extends React.PureComponent {
	render() {
		return (
                     Hello Bacancy
                )
        }
}

Optimizing JSON Data for React Native App Performance

Mobile applications always require load resources from a service or remote URL, and to accomplish such actions, programmers make fetch requests to pull data from that server.

The fetched data from private as well as public APIs returns in a JSON form that has some sort of compound nested objects. Usually, most of the programmers store the same JSON data for local offline access, and the performance suffers because JS applications render JSON data slowly.

So, I would like to advise you to convert raw JSON data into simpler objects before rendering.

Copy Text
fetch('SomeURL', {
 method: 'POST',
 headers: {
    Accept: 'application/json',
   'Content-Type': 'application/json',
 },
 body: JSON.stringify({
   firstParam: 'yourValue',
   secondParam: 'yourOtherValue',
 }),
}).then((response) => response.json())
  .then((responseJson) => {
       // Use JSON.parse Method To Convert Response in Object 
       var response = JSON.parse(responseJson);
       return response;
     })
   .catch((error) => {
     console.error(error);
   })

Use NativeDriver Animation

Animations in React Native look good and are easy to create. As the animated library lets you sanction the native driver, it will send the animations over the bridge to the native side before the animation starts.

Animations will execute the main thread independently of a blocked JavaScript thread; it will result in a smoother experience and fewer frame drops.

Change use Native Driver to the animation configuration. This is how a regular animation performs;

  • JavaScript driver uses requestAnimationFrame to execute on every frame
  • Intermediate values are calculated and passed to the View
  • The View is updated using setNativeProps
  • JS sends these changes to the native environment through the bridge
  • Native updates UIView or Android.View

But, Native Driver Animation works like this.

  • The native animation driver uses CADisplayLink or android.view.Choreographer to execute on every frame
  • Intermediate values are calculated and passed to a view
  • The UIView/android.View is updated
Copy Text
Example :
	Animated.timing(
            this.state.fadeAnim, {
            toValue: 1,
            userNativeDriver: true,
           }
        ).start()

< Animated.ScrollView // <-- Use the Animated ScrollView wrapper
  scrollEventThrottle={1} // <-- Use 1 here to make sure no events are ever missed
  onScroll={Animated.event(
    [{ nativeEvent: { contentOffset: { y: this.state.animatedValue } } }],
    { useNativeDriver: true } // <-- Add this
  )}
>
  {content}
< /Animated.ScrollView >

Reduce Application Size

React Native uses external and component form libraries to impact application size. To reduce the size, you have to optimize the resources, use ProGaurd to create different app sizes for different device architectures, and compress the graphics elements, i.e., images.

You can follow below common practices for reducing app size and can improve the React Native performance:

  • Move components from the native realm to the React Nativerealm.
  • The components on the JavaScript side use a bridge to communicate with the Native side.
  • Reduce the load on the bridge and improve the React Native app performance.
  • Check the stability of open-source libraries before you use them. Boilerplate codes in libraries often slow down the rendering performance.
  • Some components make heavy use of message queues while communicating with the Native side, so you should not pass them on to the main thread.

So now, you know exactly where to attack to optimize React Native performance. But wait! There are more approaches you need to know in React Native app performance optimization for Android and IOS.

Let’s quickly go through the top 5 ways to reduce the application size to optimize Android and IOS Performance

Leverage our result-oriented React Native development services to get rid of the technical headaches.
Being the most prominent React Native development company we will help you build exceptional mobile apps that lead you to Android Play and iOS app store.

Top 5 Ways to Reduce Android App Size and Optimize Performance

To ensure that your enterprise application stands victorious in the market, here are the best 5 ways you should consider reduce android app size and it will help you to monitor the performance of React Native.

Android App Performance:

1. Strict Mode:

Strict mode is generally used for network requests detection or accessing disk from the main thread. You can also use detectAll(), if you want to detect all the probable issues it can find.

Here is a short snippet of how it looks like

Copy Text
public void onCreate() {
 if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate();}

2. Selecting the Correct Data type:

If you require a thread-safe collection, allowing only one thread to work at a time, you should choose Vector. The benefit is that it is synchronized.

For cases other than that, you should go with ArrayList, there is a specific cause for you to use vectors. Here is the snippet

Copy Text
@Override
public int compareTo(Object object) {
Meal meal = (Meal) object;
if (this.timestamp < meal.getTimestamp()) {
return -1;
} else if (this.timestamp > meal.getTimestamp()) {
return 1;
}
return 0;
}

3. Reflection:

To understand in simple terms, reflection is the potential of class and objects to examine their constructors, field, methods. etc. Generally, reflection is used to check whether a given version is available for a specific OS version, and for backward compatibility. If you want to use this approach, ensure that the response is cached, since it is pretty slow.

4. ViewHolders:

I cannot overlook this one, even though you may be aware of this. The Viewholder design pattern aids in smoothening the scrolling lists. It facilitates view caching that can remarkably decrease calls to findViewById() and increase views by retaining them.

It looks something like this.

Copy Text
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, viewGroup, false); viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText("Hello World");

5. Image resizing:

When you take a picture on your phone, the image’s actual resolution is more than the display’s resolution. Since the device, it is displayed on is relatively smaller. It is necessary to resize them because you will run out of memory soon if you try displaying them on full resolution.

Pro tip: inJustDecodeBounds is a useful Bitmap flag that allows you to see the resolution of the bitmap. Let’s suppose that your bitmap is 1024×768, and the display ImageView is just 400×300.

In such a case, you should divide the bitmap’s resolution by 2 until it becomes lesser than or equal to the ImageView. The bitmap you will get will be 512×384. Another benefit is that the downsampled bitmap uses four times lesser memory, which helps you avoid the ‘OutOfMemory’ error.

Best 5 Tips to Reduce iOS App Size and Optimize performance

iOS App Performance:

1. Clear cache:

According to the HTTP headers, NSURLConnection caches resources on disk or in memory as it processes. You can manually create an NSURLRequest and load it with cached values.

Check out this go to snippet you can work with:

Copy Text
+ (NSMutableURLRequest *)imageRequestWithURL:(NSURL *)url {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.cachePolicy = NSURLRequestReturnCacheDataElseLoad; // this will make sure the request always returns the cached image
    request.HTTPShouldHandleCookies = NO;
    request.HTTPShouldUsePipelining = YES;
    [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
    
    return request;
}

2. Reuse Expensive iOS Objects:

Reuse Expensive iOS Objects prevent performance bottlenecks while working with the objects. You should reuse these objects by either adding a property to your class or creating a static variable.

Two such examples are NSDateFormatter and NSCalendar. Although when analyzing dates from a JSON/XML response, you can’t always refrain from using them.

Copy Text
// in your .h or inside a class extension
@property (nonatomic, strong) NSDateFormatter *formatter;
// inside the implementation (.m)
// When you need, just use self.formatter
- (NSDateFormatter *)formatter {
if (! _formatter) {
 _formatter = [[NSDateFormatter alloc] init];
_formatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy"; // twitter date format
    }
    return _formatter;
}

3. Set Relevant Background Images:

You should use a UIImageVIew, if you have a full-sized background image. This is because UIColor’s colorWithPatternImage is enabled to create repeated small pattern images. UIImageView reduces a chunk of memory in such cases.

Copy Text
// You could also achieve the same result in Interface Builder
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background"]];
[self.view addSubview:backgroundView];

4. Set the Shadow Path:

To determine the precise shape of your view prior to dropping shadow rendering, the Core Animation has to do an offscreen pass. However, this operation is quite expensive.

A better alternative to this is a much easier system to render: setting the shadow path.

Copy Text
view.layer.shadowPath = [[UIBezierPath  bezierPathWithRect:view.bounds] CGPath];

5. Avoid Date Formatters Where Possible

You need to tread carefully, if you have a lot of dates to parse with the NSDateFormatter. As I have mentioned above, it is always wise to reuse NSDateFormatters whenever and wherever you can.

You can easily transform this timestamp into an NSDate, as shown below:

Copy Text
- (NSDate*)dateFromUnixTimestamp:(NSTimeInterval)timestamp {
    return [NSDate dateWithTimeIntervalSince1970:timestamp];

You have explored almost all the aspects in-depth to optimize your React native performance for Android and iOS. The story isn’t over yet! There are additional features that could complement your React Native app performance improvements.

Top 6 Additional Features To Optimize React Native Performance

Features of react native app performance

Here are the various categories of features that you might want to add to your Android and iOS apps. You will need your client’s developer account access and various technologies to implement any type of integration.

We’ve assembled a list of additional features that you might want to integrate into your existing React Native mobile app so that your users stay connected to your app.

Let us check out the tech stack needed for 6 different add-ons in your app.

Social media Integration:

You might want to integrate and link your app with the user’s social media/networking accounts.

The tech-stack your React Native developer will demand will be like: Apple Integration- Apple Developer Account Google Integration – Google Developer Account, Firebase Developer Account Facebook Integration- Facebook Developer Account Instagram Integration- Facebook Developer Account LinkedIn Integration- LinkedIn Developer Account Twitter Integration- Twitter Developer Account.

For example, to integrate LinkedIn with your React Native app, you will need access to your client’s LinkedIn developer account

LinkedIn with your React Native app

Communication tools:

You might want to add communication tools in your apps like – Sign-up and log in, Contact us, Support/Inquiry form, Polling/Petition, Subscription, New alerts/updates via push notifications, Appointments, Book the service, etc.

Tech-stack, your React Native developer, will need to add such features in your app will be: New Alerts/Updates Via Push Notification

  • Firebase Developer Account
  • Apple Developer Account (Notification in IOS)
  • Node JS(Backend Technology and Database Management)

Contact us

  • Node JS(Backend Technology and Database Management) for Email Sending
  • Call

Support/Inquiry form

  • Redux-Form, Redux, redux-thunk
  • Node JS(Backend Technology and Database Management) for Email Sending
  • Firebase Developer Account for Notify via Push Notification

Appointments

  • Redux
  • Node JS(Backend Technology and Database Management) for Email Sending
  • Firebase Developer Account for Notify via Push Notification

Check out the Firebase developer account dashboard,

Firebase developer account

Information tools:

Search feature, About us, Find our location/Google-indoor maps, Directories, PDF Viewer, Events calendar, Visiting hours/Holidays,

Our team profiles, Property/Vehicle listing, Testimonials, and more. To add such informative tools in your app, the tech-stack will be like this: Find our location/Google-indoor maps

  • Google Developer Account & Enable Google API’s

PDF Viewer

  • react-native-pdf and rn-fetch-blob required libraries

Event Calendar

  • Required react-native-calendars library
  • Firebase Developer account for event notification

Visiting Hours/Holidays

  • Required react-native-calendars library
  • Firebase Developer account for holiday notification

For example, check the google developer account for integrating Google Maps,

google developer

Payment options:

Additional payment features after you have launched your app like Payment gateway Integrations, Easy checkouts, QR/Barcode Scanner Integrations, and more. Tech-stack Requirements: Payment gateway integration

  • Stripe for Credit / Debit Card and Bank Account (Stripe Developer Account)
  • Stripe Connect for Payment Summary (Stripe Developer Account)
  • Google Pay Integration (Google Developer Account)
  • Apple Pay Integration (Apple Developer Account)

Easy Checkout

  • Paypal Integration
  • Paypal Developer Account
  • Stripe / Braintree Developer account

QR / Barcode Scanner Integration

  • Required react-native-camera and react-native- qrcode-scanner libraries.

For example, see the PayPal developer account dashboard,

Paypal

Reporting tools:

To add reporting tools to your existing React Native application, your developer will just need customization in your development code.

You can include add-ons like
✔ Work offline reports
✔ Absence reporting
✔ Expense claims
✔ Permission/Pay Invoice
✔ Leave requests
✔ Day-to-day activity reports

Reporting tools

Measurements tools:

Your app may need some calculations related to banking, education, finance, or health. Tools like Loan calculator, BMI calculator, Job quote, or User feedback.

Such integration of measurement tools can be achieved customarily in your React Native app code. Tech-stack foadd Feedback: Node JS(Backend Technology and Database Management) for Email addou add subaddress, you will realize the true potential of your React Native app. More of your users will now be spending more time on your app, which will benefit your business.

So, by now, you have grasped why React Native is the ultimate choice for optimizing your mobile app performance. Once you have experienced the wonders of Native app vs. React Native app performance, you will not respond to any other frameworks.

Final words

If you are convinced that your users require these personalized features in your existing app, React Native is your best friend. All you need is a renowned React Native development company to improve the App performance of React Native testing by adding enhancing features to your application.

Bacancy Technology is a globally renowned software development company and a one-stop solution to Hire React Native developer to turn your ideas into a viable business solutions. Our offshore React Native app developers are well-versed in understanding global clients’ MVPs and have successfully delivered a wide range of products. Uplift your React Native app performance by optimizing your app with customized functionalities.

Frequently Asked Questions (FAQs)

To optimize the FlatList, you should:

  • Avoid using arrow functions inline for render item.
  • Not use 1080P HD images in the list.
  • Optimize maxToRenderPerBatch prop
  • Improve window size prop
  • Use getItem Layout

1. Avoid costly re-renders
2. Use < FlatList >, < SectionList >, < VirtualizedList > instead of < ListView >, < ScrollView >
3. Keep in mind to upgrade React Native to the newest version.
4. Decrease the Application Size.
5. Enhance your images.

As per the documentation, removeClippedSubviews is a special improvement property open to view by RCTView. It is useful for content scrolling when there are many subviews, most of which are offscreen.

PureComponent exclusively handles the shouldComponentUpdate method for you; the rest is similar to Component. PureComponent will simply compare when there is a change in props or state.

Looking to Improve Your Existing App’s Performance?

Hire React Native developer to optimize your app performance.

Connect Now

Get In Touch

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?