Mastering React Native Apps: useMemo, useCallback, and FlashList

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.

Memoization

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:

  • Improve Performance: By preventing unnecessary re-renders, your app runs smoother and faster.
  • Efficient Resource Usage: Reduces CPU usage and memory consumption by avoiding repetitive calculations of how many times it should be rendered.
  • Enhanced User Experience: Faster and more responsive user interface in React Native apps.

Now, the next question in the minds of Developers will be when should we useMemo?

  • Components Have Expensive Calculations: If your component does a lot of processing or calculations.
  • Frequent Re-Renders: When a component re-renders often but its output doesn’t change frequently.
  • Pure Components: Components that render the same output for the same props can benefit the most.

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.

useCallback

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?

  • Passing Functions as Props to Child Components: If a parent component passes a function to a child component, the child component might re-render unnecessarily if the parent re-renders. Using useCallback can prevent this by ensuring the function reference remains the same unless its dependencies change.
  • Performance Optimization: When a function is expensive to re-create or you want to avoid creating new functions on every render, useCallback can help.

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.

Accelerate Your React Native Development. Hire Our Deveopers Now!

FlashList

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:

  • Memory efficient scrolling.
  • Snappy on all platforms.
  • Extra configuration for even better performance.
  • Buttery smooth complex layouts.

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:

Performance

FlatList:

  • Rendering Performance: FlatList uses lazy loading, meaning it only renders the items that are currently visible on the screen. This reduces the initial rendering time and improves performance for large lists.
  • Efficiency: While FlatList is efficient for most use cases, its performance can degrade when handling extremely large lists or complex item layouts.
  • Memory Usage: FlatList manages memory usage effectively by reusing views that go off-screen, but it can still consume a significant amount of memory if not optimized properly.

FlatList:

  • Rendering Performance: FlashList is optimized for rendering extremely large lists quickly and efficiently. It leverages advanced rendering techniques to improve performance significantly.
  • Efficiency: FlashList is designed to handle complex layouts and large datasets with minimal performance degradation. It is more efficient than FlatList in scenarios involving extensive data.
  • Memory Usage: FlashList is more aggressive in its memory management, reducing the overall memory footprint even for large datasets.

Use Cases

FlatList:

  • General Use: Ideal for general-purpose list rendering where performance is not a critical concern.
  • Small to Medium Lists: Suitable for small to medium-sized lists where the data size and complexity are manageable.
  • Simple Layouts: Works well with simpler item layouts and straightforward list structures.

FlashList:

  • Performance-Critical Applications: Best for applications where performance is crucial, especially with large datasets.
  • Large Lists: Excels in handling very large lists with complex item layouts without sacrificing performance.
  • Advanced Layouts: Ideal for use cases requiring advanced item layouts and interactions.

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.

coma

Conclusion

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.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?