In the world of React Native application development, it has become necessary to make your apps faster, more reliable, and deliver a smoother user experience. In this world where performance is king, users expect fast experiences, so as React Native developers we have to deliver.
However, achieving this is a challenging task, especially when you have to deal with complex state management and re-renders throughout the React Native application. This is where hooks like useMemo, and useCallback, and components like Flashlist come into play.
In this article we will try to understand and learn to apply practical strategies for enhancing React Native application performance using these tools and also explore how these tools help us to prevent unnecessary re-renders, so let’s dive in.
When we say useMemo means we are doing ‘Memoization in React Native or React in general’, we are using this technique to optimize the performance of our application’s components. The main purpose of this technique is to avoid unnecessary re-renders which slows down the performance.
When we are moving forward we need to understand why we need Memoization in React Native in the first place. For understanding, these are the 3 main reasons have a look:
Now, the next question in the minds of Developers will be when should we useMemo?
Now, we will see how to use it:
Firstly, make a screen where you make the React Native component that you want to render.
1. Import React from ‘react’:
import React from 'react';
2. Create a Functional Component:
import React from 'react';
import {FlatList, SafeAreaView} from 'react-native';
import ListItem from '../../components/ListItem';
const UseMemoDemoScreen: React.FC = () => {
const items = [
{id: 1, name: 'Test '},
{id: 2, name: 'Test '},
{id: 3, name: 'Test '},
{id: 4, name: 'Test '},
{id: 5, name: 'Test '},
{id: 6, name: 'Test '},
{id: 7, name: 'Test '},
];
return (
<SafeAreaView>
<FlatList
data={items}
renderItem={({item}) => <ListItem item={item} />}
keyExtractor={item => item.id.toString()}
/>
</SafeAreaView>
);
};
export default UseMemoDemoScreen;
3. After creating the functional component we create another reusable component that we will use which is memoized:
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import Colors from '../theme/Colors';
const ListItem = React.memo(({item}) => {
console.log('Rendering ListItem:', item.name); // This will show
you how often the component re-renders
return (
<View>
<Text style={styles.textColor}>{item.name}</Text>
</View>
);
});
const styles = StyleSheet.create({
textColor: {
color: Colors.black,
},
});
export default ListItem;
Here you can notice that we have wrapped this component in a React.memo.
You can also write this component in this format:
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import Colors from '../theme/Colors';
const ListItem = ({item}) => {
console.log('Rendering ListItem:', item.name); // This will show you how
often the component re-renders
return (
<View>
<Text style={styles.textColor}>{item.name}</Text>
</View>
);
};
const styles = StyleSheet.create({
textColor: {
color: Colors.black,
},
});
export default React.memo(ListItem);
In, the above example we have seen the memoization of the entire component. We can also memoize a single function using useMemo hook, here’s how you do it.
import React, {useMemo} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import Colors from '../theme/Colors';
const ListItemComponent = ({item}) => {
console.log('Rendering ListItem:', item.name);
return (
<View>
<Text style={styles.textColor}>{item.name}</Text>
</View>
);
};
const ListItem = useMemo(() => {
return React.memo(ListItemComponent, (prevProps, nextProps) => {
return prevProps.item.name === nextProps.item.name;
});
}, []);
const styles = StyleSheet.create({
textColor: {
color: Colors.black,
},
});
export default ListItem;
So, let’s see the result:
This is the first time, It renders the component, in this case just to understand we have added console.log and printed it on the console.
If we again try to render it with the same props then it will give results like this empty console, nothing gets printed on the console because it is memoized.
On your phone screen it will look like this:
So, this is how useMemo Hook works.
When we say we are using useCallback hook we are using a feature from React that helps us to optimize the performance of your application by memoizing (caching) functions. This hook is used to prevent unnecessary re-creations of functions when a component re-renders.
Let’s understand in detail step by step:
Firstly, what is useCallback ?
useCallback is a React hook that returns a memoized version of a callback function. This means the function created using useCallback will only change if one of the dependencies has changed.
Secondly, why use useCallback hook in the first place?
Using useCallback helps with performance optimization by preventing unnecessary function re-creations and avoiding unnecessary re-renders of child components. This can make your application run more smoothly, especially in complex applications with many components.
If I try to explain to you in layman’s terms then Imagine you have a list of tasks, and every time you check the list, you rewrite the entire list even if nothing has changed. This would be very inefficient. Instead, you could use a sticky note to remember what the list looked like the last time you checked. You only rewrite the list when there’s an actual change in tasks.
useCallback works similarly for functions in React. It uses a “sticky note” to remember the function you created, and it only creates a new one if something in the list of dependencies (like the task list) has changed.
When and Where should we use useCallback hooks?
Now, we will show you how to use useCallback hooks:
import React, {useCallback, useState} from 'react';
import {SafeAreaView, StyleSheet, TouchableOpacity, Text} from 'react-native';
import Colors from '../../theme/Colors';
const UseCallbackDemoScreen: React.FC = () => {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count => count + 1);
console.log('Button clicked!', count);
}, [count]);
return (
<SafeAreaView>
<TouchableOpacity
style={styles.button}
onPress={() => {
handleClick();
}}>
<Text style={styles.buttonColor}>useCallback Demo</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
export default UseCallbackDemoScreen;
const styles = StyleSheet.create({
button: {
paddingHorizontal: 20,
paddingVertical: 10,
borderWidth: 1,
borderRadius: 25,
margin: 20,
},
buttonColor: {
color: Colors.black,
},
});
This is a very small demo that we have provided to you. If we see official documentation then it is written straight that when you use renderItem props, that same function should be wrapped inside useCallback hook.
import React, {useCallback, useState} from 'react';
import {
SafeAreaView,
StyleSheet,
TouchableOpacity,
Text,
FlatList,
View,
} from 'react-native';
import Colors from '../../theme/Colors';
const UseCallbackDemoScreen: React.FC = () => {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count => count + 1);
console.log('Button clicked!', count);
}, [count]);
const renderItem = useCallback(({item, index}) => {
return (
<View key={index}>
<Text>{item}</Text>
</View>
);
}, []);
return (
<SafeAreaView>
<TouchableOpacity
style={styles.button}
onPress={() => {
handleClick();
}}>
<Text style={styles.buttonColor}>useCallback Demo</Text>
</TouchableOpacity>
<FlatList
viewabilityConfig={{
waitForInteraction: false,
viewAreaCoveragePercentThreshold: 70,
}}
data={count}
renderItem={renderItem}
numColumns={1}
horizontal={false}
keyExtractor={item => item.media_id}
contentContainerStyle={{
padding: 20,
paddingTop: 42,
}}
/>
</SafeAreaView>
);
};
export default UseCallbackDemoScreen;
const styles = StyleSheet.create({
button: {
paddingHorizontal: 20,
paddingVertical: 10,
borderWidth: 1,
borderRadius: 25,
margin: 20,
},
buttonColor: {
color: Colors.black,
},
});
You can see that the dependency array is empty. This indicates no props are sent while.
We use something only when props change and we have to render the whole UI.
Let’s consider a real-life example:
const handleAddToCart = useCallback(() => {
setCart((prevCart) => [...prevCart, item]);
}, [item]);
In this handleAddToCart function, we used useCallback we ensured that this function is not recreated on every render, but only when the item details or cart state change.
If you know FlatList then don’t worry you also know FlashList. FlashList is just another and better alternative to FlatList.
FlashList is 5x faster than Flatlist in FPS* in UI Thread and 10x faster than Flatlist in FPS* in JS Thread.
It is very efficient in the following:
Our sole aim is to make apps faster, and for that performance becomes necessary.
FlatList and FlashList are both components used in React Native for rendering lists.
However, they have some key differences in terms of performance, features, and use cases. Here’s a detailed comparison:
FlatList:
FlatList:
FlatList:
FlashList:
Now, let’s see how to use FlashList in our Applications:
Step 1: Install packages and Dependencies.
yarn add @shopify/flash-list cd ios && pod install
Or
npm i @shopify/flash-list
Step 2:
import {FlashList} from '@shopify/flash-list';
import React from 'react';
import {View, Text, StyleSheet, SafeAreaView} from 'react-native';
const data = [
{id: '1', title: 'Item 1'},
{id: '2', title: 'Item 2'},
{id: '3', title: 'Item 3'},
];
const FlashListScreen: React.FC = () => {
const renderItem = ({item}) => (
<View style={styles.item}>
<Text style={styles.title}>{item.title}</Text>
</View>
);
return (
<SafeAreaView style={styles.container}>
<FlashList
data={data}
renderItem={renderItem}
keyExtractor={item => item.id}
estimatedItemSize={50}
/>
</SafeAreaView>
);
};
export default FlashListScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 20,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
The outcome is as follows.
In conclusion, optimizing React Native applications for performance involves leveraging powerful tools like useMemo, useCallback, and components such as FlashList. By utilizing memoization with useMemo and useCallback, we can prevent unnecessary re-renders and enhance the efficiency of our applications. These hooks help in managing complex states and maintaining smooth, responsive user interfaces, especially in performance-critical scenarios.
Furthermore, adopting FlashList over FlatList can significantly boost performance, particularly with large datasets and complex layouts. Its advanced rendering techniques and efficient memory management make it an ideal choice for building high-performance mobile applications.
As mobile developers, our goal is to deliver fast, reliable, and smooth user experiences. By incorporating these strategies and tools, we can create applications that not only meet user expectations but also stand out in a competitive market. Embracing these performance optimization techniques is essential for developing robust and scalable mobile applications.
How to Effectively Hire and Manage A Remote Team of Developers.
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork