How to cache images in React Native with react-native-fast-image

Introduction

We'll learn how we can cache our images in our React Native application so as to improve the performance of our mobile application.

Installation

In order to implement caching in our React Native application, we need to use a package called react-native-fast-image. This package will allow us to cache our images.

Let's use the following commands to create a React Native application:

  • npx react-native init cacheExample
  • cd cacheExample

Next, let's use the command mentioned below to install the package react-native-fast-image.

  • npm i react-native-fast-image

Explanation

  • Now let’s use this package in our project and load an image inside our project, which is stored in our database. This will load the particular image over the internet each time when the component is loaded.
  • This will decrease the performance of the application when the user’s internet connection is slow.
  • In order to overcome this drawback, we can employ react-native-fast-image to cache the image when we load an image from our database (or from the internet).
  • When our component loads again, our image will be fetched from the cache rather than from the database. This will save us bandwidth, which in turn will save cost and improve the performance of our application which will improve user experience.

    Code

    import {View} from 'react-native';
    import React from 'react';
    import FastImage from 'react-native-fast-image';
    const App = () => {
    return (
    <View>
    <FastImage
    style={{width: 300, height: 300}}
    source={{
    uri: 'https://images.unsplash.com/photo-1600682575515-c5624e1f885a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8',
    priority: FastImage.priority.normal,
    }}
    resizeMode={FastImage.resizeMode.contain}
    />
    </View>
    );
    };
    export default App;

    Explanation

    • Lines 1–3: We import necessary packages like react-native-fast-image.
    • Lines 5–20: We implement the FastImage tag with the source prop to set the URL of our image, and the priority: FastImage.priority.normal props to implement whether the image needs to be retrieved faster or not.
    • Here we have implemented the Fast-image tag given react-native-fast-image. So when our component loads, this image will be fetched from Unsplash, but when the component loads again the image will be fetched from the cache which will improve the user experience by faster loading from the cache rather than fetching the image from the internet.

    Conclusion

    This is how you can use react-native-fast-image package to implement caching inside your React Native application

    Free Resources