Learn how to improve performance, reduce startup time, and reduce package size and memory usage of React Native applications. @[TOC](How to improve React Native App performance)
1. Use of Hermes
Hermes is an open source JavaScript engine optimized for React Native. Hermes integration helps reduce startup time, memory usage, and application size.
With Hermes, your application will start twice as fast, memory usage will be reduced to 30%, Android package size will be reduced by 30%, and iOS application performance will be improved.
Let’s see how to integrate Hermes. Hermes supports iOS after version 0.64. Therefore, be sure to Upgrade your application using the React Native Upgrade Helper.
Enable Hermes Android – How to use
Add the following line of code to android/app/build.gradle: project.ext.react = [entryFile:"index.js",
- enableHermes: false // clean and rebuild if changing
+ enableHermes: true // clean and rebuild if changing
]
Copy the code
If you use ProGuard, add the following rules to proGuard-rules.pro:
-keep class com.facebook.hermes.unicode. * *{*; } -keepclass com.facebook.jni. * *{*; }Copy the code
Clean up the building
cd android && ./gradlew clean
Copy the code
IOS – How to use
Edit the ios/Podfile with the following line of code - use_react_native! (:path= > config[:reactNativePath],
# to enable hermes on iOS, change false to true and then install pods
- :hermes_enabled= > false
+ :hermes_enabled= > trueInstall Hermes Pod CD ios && Pod installCopy the code
That’s it, now create your iOS and Android versions and look at application startup speed, memory usage, and specific package sizes.
2. Avoid re-rendering using useMemo
UseMemo hooks help developers avoid rerendering child components to improve React application performance. UseMemo is used to handle memorization, which means that if any component receives the same props multiple times, it will use the previously cached props and render the JSX view and return the component.
In the example below, I use FlatList and Button. The first Flatlist appears perfectly. Now, when the user presses the button, the new setCount updates the status variable, and the entire component reloads the FlatList even if there are no value updates in the Array. To avoid this, I wrap FlatListItem (UseMemoListItem) with useMemo, so useMemo checks for any changes in props, and then it only renders JSX, otherwise it will return to render and return the props before the view. The code is as follows:
const technology = [
{ name: 'React Native' },
{ name: 'React.js' },
{ name: 'Next.js'},];const [arrTechnology, setArrTechnology] = useState(technology);
const [count, setCount] = useState(0);
function UseMemoListItem({item, onChange, arrTechnology}) {
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={arrTechnology}
keyExtractor={(item)= > String(item.name)}
renderItem={({item, index}) => (
<UseMemoListItem
item={item}
/>
)}
ItemSeparatorComponent={() => <UseMemoListItemSeprator />}
showsVerticalScrollIndicator={false}
/>
</View>
);
Copy the code
3. Use cached images
The React Native Image component allows developers to display images in applications, but there are still some issues, such as –
React Native supports built-in caching for iOS by enabling the following lines of code. The code is as follows:
<Image
source={{
uri: 'https://example.com/image.png'.cache: 'only-if-cached'
}}
style={{ width: 400.height: 400}} /> For what Android should do, however, there is a popular third-party library called -react-native -fast-image, which is perfect for iOS and Android. With Fast Image, you can provide application users with Fast Image rendering, caching mechanisms, and more.import FastImage from 'react-native-fast-image'
const YourImage = () = > (
<FastImage
style={{ width: 200.height: 200 }}
source={{
uri: 'https://yourimageurl.com/image.png',
headers: { Authorization: 'token'},priority: FastImage.priority.normal,}}resizeMode={FastImage.resizeMode.contain}
/>
)
Copy the code
4. Use nativeDriver with the animation library
We use animation in our applications, but sometimes it doesn’t work as expected, which can affect application rendering performance. To avoid flicker and run a smooth animation, use the NativeDriver, which sends the animation to the local bridge before it starts on the component. This helps execute animations on separate javascript instances, resulting in smoother animations. The following code
// Integration is very simple - useNativeDriver: true
Animated.timing(this.state.animatedValue, {
toValue: 1.duration: 500.useNativeDriver: true.// <-- Add this
}).start();
Copy the code
Use Redux/MobX/Apollo for state management
Many times the need to manage data locally means caching data that is immediately displayed to the user without interruption when the user returns to the application. We are using AsyncStorage, local database storage to store data, and the next time the user comes back/opens the application, we are getting the data and saving it in global variables to access anywhere in the application.
To manage it across various screens and store data in various arrays, the object prefers popular state-management libraries such as Redux, Redux Rematch, MobX, and Apollo. These libraries will store management | | to retrieve the data for you, you can easily access the entire application without interruption.
6. Delete console logs
We use console.log(‘ Hello React! ‘) to debug the application. If we keep console.log() when deploying the application, it will cause performance problems due to javascript threads.
To remove console.log in production, follow simple installation and setup.
npm install babel-plugin-transform-remove-console
Copy the code
Now modify the.babelrc file to remove the console statement as follows:
{
"env": {
"production": {
"plugins": ["transform-remove-console"]}}}Copy the code
7. Optimize your Android app size
The React Native Android app contains – images, fonts, and more. Four different binaries compiled for different CPU architectures Javascript packages with business logic other built-in files this will combine all of this and create a binary for you as you build your application. Optimize binary size Android builds in React Native by adding the following line
Update the following lines in Android /app/build.gradle
def enableProguardInReleaseBuilds = true
Copy the code
If you want to extract four different binaries based on your CPU architecture,
def enableSeparateBuildPerCPUArchitecture = true
Copy the code
Thanks for reading this blog 😀😀😀 see 😴 😀 next time!!