Coding

Published on March 12th, 2022 | by Bibhuranjan

0

React Native Performance Optimization

React Native is an application development platform that allows developers to construct mobile apps with agility and speed. React Native, like any other framework, has several flaws that cause significant application performance issues.

Any product’s performance is critical. Facebook, Shopify, Tesla, and Discord are just a few hugely successful firms that use React Native. React Native is a potential cross-platform application development framework. So, why are the world’s largest corporations gravitating toward React Native?

  • It provides code that is more concise and easier to understand and can be shared across different platforms.
  • It allows for quick iteration without the need for a compilation cycle.
  • You’ll be able to ship faster and focus on the details that count, resulting in an app that looks and feels great.

Optimizing React Native can be difficult for individual developers. However, you can hire React Native developers from a dedicated IT company with proven experience optimizing react-native solutions for different industries. This article will go through some best practices for making your React Native app faster and more efficient.

Tips for React Native performance Optimization

With the help of various code samples, let’s look at some of the best practices for boosting the performance of a React Native application.

Memory Leaks

Memory leaks in your react native app can happen for various reasons. Take, for example, scrolling in a hybrid Android music app. For example, scrolling down the song list to the third page causes the program to freeze RAM on mobile, resulting in performance degradation. Because both procedures take place on separate portions, transmitting data between them through a bridge takes a long time.

Instead of utilizing ListView, you can use FlatList or VirtualizedList. FlatList in React Native is especially useful when:

  • Pagination with no limit to the number of pages that can be scrolled indefinitely
  • Smooth rendering performance is required when pulling to refresh.

While the efficiency of FlatList in React Native is impressive for the vast majority of use cases, developers can also use SectionList to create a better scrolling experience.

Improve StartUp Time

The time it takes for an app to pull content from its database is app startup time. The startup time can be improved by reducing the size of the bundle. By improving the app’s start time, we can improve its performance.

Enabling the Hermes in Android

­ project.ext.react = [

entryFile : “index.js”,

– enableHermes: false // If you’re modifying, clean it up and build it

+ enableHermes: true // If you’re modifying, clean it up and build it

]

Add the following rules to proguard-rules.pro if you’re using ProGuard:

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

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

Cleaning the structure is the next step:

cd android && ./gradlew clean

Deploy the app

npm react-native run-android

Use Slowlog to Optimize performance

When it comes to viewing rendering performance in your project, React Native Slowlog is a godsend. You can use the tool to create a custom threshold as a starting point for performance improvements. Start using React Native performance profiling by adding the following code to the view constructor.

slowlog(this, /.*/)

Use <Flatsize> <Sectionlist> in place of <ListView> <Scrollview>

Instead of <Listview>, it’s better to use less RAM for improved performance. Because the rendering of the listview is slow.

  • SectionList (flat list) (expands FlatList with additional section headers).
  • The list that’s been virtualized (should be used only if you need to work on nonstandard data not supported by FlatList)
  • They also have many features like pull to refresh, horizontal mode, scroll loading, header/footer support, and so on.

The data and render item are the two main props that these components accept and require. The first attribute is a date, an array of data with each element representing list item data. The second prep renders item extracts one from the source, and produces a formatted render component.

<FlatList

data={

[

{ id: 1, title: ‘It Aint’t Me Baby’ },

{ id: 2, title: ‘Souls Unfactured’ }

]

}

renderItem={({ item }) =>

<BookItem title={item.title} />}

/>

Prevent costly re-renders.

When a component’s state or properties change, React re-renders the whole Virtual DOM subtree by default. Try the following approaches to reduce unwanted and costly re-renderings while improving the app’s performance.

ShouldComponentUpdate()

When a component’s state or properties change, React re-renders the whole Virtual DOM subtree by default. Try the following approaches to reduce unwanted and costly re-renderings while also improving the app’s performance.

shouldComponentUpdate (nextProps) {

const didSomePropChange =

nextProps.someProp !== this.props.someProp

return didSomePropChange

}

React.PureComponent

You may use React. PureComponent class for each component to avoid code the shouldComponentUpdate() method yourself. The render method produces the same result with the same properties and states.

Unlike the React. component class, which provides the function shouldComponentUpdate() by default, does a superficial comparison of the component’s properties and states. A shallow comparison of a deeply nested object checks the reference, not the object’s values.

The next entries work in the same way as the previous ones.

Class MyComponent1 extends React.PureComponent {

// some code

}

class MyComponent1 extends React.Component {

shouldComponentUpdate(nextProps) {

if(this.props.someProp === nextProps.someProp) {

return false;

}

return true;

}

}

React.memo()

The use of the higher-order component React. Memo is another intelligent approach for avoiding needless rendering (). It’s like React.PureComponent, but instead of classes, it’s for function components. You can wrap a functional component with React. memo for better speed if it always renders the same structure with the same properties. This indicates that React will avoid rendering this component and instead utilize the most recently rendered version.

const MyComponent1 = ({text}) => <Text>{text}</Text>;

MyComponent1.propTypes = {

text: PropTypes.string.isRequired

};

export default React.memo(MyComponent1);

The useCallBack Hook

Starting version 0.59 you can access React Hooks, allowing access to the status and other functions without having to write classes. The hook useCallBack is a great way to prevent unnecessary re-rendering.

const ComponentContainer 1= ({selectedLocation, navigation}) => {

const goToSelectedLocation = useCallback(() => {

if (!selectedLocation) {

return

}

navigation.navigate(‘DeliveryLocation’)

}, [selectedLocation])

return (

<Button

goToSelectedLocation={goToSelectedLocation}/>

)

}

Update ReactNative to the newest version

React Native’s developer, and community are constantly working to improve how it works and performs. Ensure that your project is updated to the most recent version of React Native regularly.

Performance and Application Size

The performance of your program may suffer as a result of the increased application size. This is a common issue with Android apps that rely extensively on third-party sources to function, such as numerous screens, libraries, and so on. These extra resources have an immediate effect on the size of the application, causing it to grow.

If you want to reduce the size of your react native app, you need to do the following.

  • To make the application smaller, use Proguard.
  • For specific CPU architectures, create smaller APK files. Your app users will receive the appropriate APK file for their phone’s architecture when you do this. This eliminates the need for numerous architecture-aware JSCore binaries, resulting in a smaller app.
  • Image and graphic elements should be compressed. Using file types such as APNG instead of PNG files is another option for reducing image size.
  • Raw JSON data should not be stored. Convert it into static object IDs or compress it.
  • Native libraries should be improved.

Image Optimization in React

While working with react Native, it is essential to use responsive images. Otherwise, you can end up with an app that performs poorly and displays a lot of errors. Use the smallest image size feasible. Larger files take longer to transfer and display on the screen. Compress the image with image resizing software. Remember to strike a balance between photo quality and size.

Below are some of the best practices that you can perform for optimizing image

  • Use smaller Images
  • Use PNG instead of JPG
  • Convert your Images to Webp format

Make it fast from beginning

While using React Native in the web background. Thinking of state management as you would on the web background. Cache your app state as much as you can. If possible, make your launch as quickly as possible. Cache any network request. It is recommended to previously fetch data ready when the user first opens the app, then sync in the background.

Use Fast loading image formats.

Image format, in addition to image size, can impact the performance of an application. Developers prefer JPEG and JPG formats with a web background because they allow compression. For mobile applications, however, this is not the case.

You can also reduce the number of distinct colours in each row of pixels in a PNG image. The image size could be drastically reduced as a result of this. Simply enough, the PNG format outperforms the JPG form.

The WebP format, which Google launched in 2010, is the most efficient of the three. It works in both lossless and lossy compression modes and can shrink images by 34%. Keep in mind that not all mobile devices will handle this format. Android 4.2.1 and higher devices, as well as iOS 14, are compatible.

Wrapping Up

Every React Native application relies on performance, yet it’s a complex subject to master. Performance can be affected by a variety of things, including console statements and animations and huge graphics and computationally intensive operations. It’s critical to locate and resolve memory leaks and poor performance.

To get the most out of the plethora of options for optimizing React Native applications. For optimal performance, it is suggested that you hire React Native Developers. To avoid frequent performance concerns, you can use these React Native Optimization Best practices in your next project.


Cover Image Software engineer photo created by DCStudio – www.freepik.com

Tags: , , ,


About the Author

Avatar photo

Editorial Officer, technofaq.org I'm an avid tech enthusiast at heart. I like to mug up on new and exciting developments on science and tech and have a deep love for PC gaming. Other hobbies include writing blog posts, music and DIY projects.



Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top ↑