Skip to main content

To Image & Video Caching In React Native

Saurabh Dhariwal

Saurabh Dhariwal

They say that React Native is the future of the Mobile App Development. And maybe, that is justified with all the innovations & futuristic possibilities it has been offering. One such innovative feature of React Native is that you can cache the images for offline access. This is something that React Native has recently introduced. Our bunch of React Native Developers are always fueled with curiosity to learn & adopt all that’s new. And hence, started diving into this newly announced feature & the library of image caching in React Native. 

 

It is also said that ‘Curiosity leads to discovery’ and it seems like AddWeb’s team’s curiosity of scrutinizing the tidbits of the image caching feature of React Native & a couple of libraries, led them to a new discovery. The discovery that helped them in making video caching possible. So let us share an in-depth guideline to Video & Image Caching for Offline Access in React Native. 


What is Caching? 
Caching is the act of keeping data in storage to allow retrieval without having to request the data from the original source, if that data will not change frequently.


Importance of Caching
Have you ever heard about watching a video or image, even when you’re offline? Well, that is possible because of caching. And hence, in today’s time & age, it acts as an important factor for accelerating the access of images. Below we share a handful of such significant points explaining the importance of caching: 

  • Improves the performance of the application by displaying the images/videos quickly

  • No issue of RAM memory being leaked

  • Saves the user from internet connection-related issues 

  • Making the offline accessibility of the image/videos possible

  • Reduces the unnecessary load on database & webserver

  • Accelerates the response of the application

  • Reduces the bandwidth consumption and hence, decreases the network traffic and diminishes the network congestion

A Complete Guide to Image & Video Caching in React Native

Usage of the Mobile App Caching
The application’s document directory is where the cached data is stored. This stored data in a cache can also be utilised in correlation with an application component. The fundamental purpose of this cached data is to accelerate the data retrieval performance, while cutting down on the access of the underlying slower storage layer.  


Package Used for Offline Access/Cache
Packages are needed to access any application or application feature offline. And ‘FastImage’ is one such package for image replacement for solving the issues. It is a wrapper around SDWebImage (iOS) and Glide (Android). So let us share the features of this amazing package - ‘FastImage’:

  • Fast Cache Package Features

    • Aggressively Cache Images

    • Add Authorization Headers

    • Prioritize Images

    • Preload Images

    • GIF Support

    • Border Radius

Installation of FastCache for Image Cache in React Native
Now that we’ve shared the basic details about caching, before talking about our self-created package & process of video caching, we’ll first like to share the installation steps for image caching with the use of Fast Cache. You can grasp the entire guide to the library of image caching in React Native is here


Installation of Video Caching in React Native
It is about time to share our self-created installation guide that makes the video caching possible in React Native. We’ll also like to acknowledge the creators of the two libraries, viz. React Native FS & React Native Video, for helping us in making the video caching in React Native possible. So, instead of beating around the bush, let us directly come to the point and share the entire process below:


Install react-native-fs:

npm install react-native-fs --save

 

Note: If your react-native version is < 0.40 install with this tag instead:

npm install react-native-fs@2.0.1-rc.2 --save

 

Adding automatically with react-native link
At the command line, in your project folder, type:

react-native link react-native-fs

 

Done! No need to worry about manually adding the library to your project.


Adding with CocoaPods

Add the RNFS pod to your list of application pods in your Podfile, using the path from the Podfile to the installed module:~~

pod 'RNFS', :path => '../node_modules/react-native-fs'

 

Install pods as usual:

pod install

 

Cache Video Steps in Detail 

Step 1 - Save Video for Offline Access

  • DocumentDirectoryPath (String) The absolute path to the document directory
let filename = videoUrl.substring(deviceuri.lastIndexOf("/") + 1, videoUrl.length);
let path_name = RNFS.DocumentDirectoryPath + filename;

RNFS.exists(path_name).then(exists => {
  if (exists) {
    console.log("Already downloaded");
  } else {
    RNFS.downloadFile({
      fromUrl: videoUrl,
      toFile: path_name.replace(/%20/g, "_"),
      background: true
    })
      .promise.then(res => {
        console.log("File Downloaded", res);
      })
      .catch(err => {
        console.log("err downloadFile", err);
      });
  }
});

 

NOTE: toFile :  Local filesystem path is having white space then it cause to play video. So you need to replace white space to any character or _ [underscore].
 

Step 2 - Get the Video from Storage

let fileName = videoURL.substring(videoURL.lastIndexOf("/") + 1, videoURL.length);

this.getVideoUrl(videoURL, fileName)
  .then(res => {
    this.setState({ videoUri: res });
  })
  .catch(url => {
    this.setState({ videoUri: url });
  });


getVideoUrl = (url, filename) => {
  return new Promise((resolve, reject) => {
    RNFS.readDir(RNFS.DocumentDirectoryPath)
      .then(result => {
        result.forEach(element => {
          if (element.name == filename.replace(/%20/g, "_")) {
            resolve(element.path);
          }
        });
      })
      .catch(err => {
        reject(url);
      });
  });
};

 

  • Use react-native-video
import Video from "react-native-video";

<Video
  source={{ uri: this.state.videoUri }} // Can be a URL or a local file.
  ref={ref => {
    this.player = ref;
  }} // Store reference
  onError={this.videoError} // Callback when video cannot be loaded
/>;

 

Notes:
DownloadFileOptions:

  •   fromUrl: string;          // URL to download file from

  •   toFile: string;           // Local filesystem path to save the file to

  •   headers?: Headers;        // An object of headers to be passed to the server

  •   background?: boolean;     // Continue the download in the background after the app terminates (iOS only)

  •   discretionary?: boolean;  // Allow the OS to control the timing and speed of the download to improve perceived performance  (iOS only)

  •   cacheable?: boolean;      // Whether the download can be stored in the shared NSURLCache (iOS only, defaults to true)

  •   progressDivider?: number;

  •   begin?: (res: DownloadBeginCallbackResult) => void;

  •   progress?: (res: DownloadProgressCallbackResult) => void;

  •   resumable?: () => void;    // only supported on iOS yet

  •   connectionTimeout?: number // only supported on Android yet

  •   readTimeout?: number       // supported on Android and iOS


Essentials from the server-side framework
There are no more overhead from server-side programming language because if the image/video URL does not match with the saved asset then caching package will separately download it and save into application local storage.


Concluding Words
The mobile application development team of AddWeb has always been high on curiosity & coming up with solutions, ahead of the time. We’re highly thankful to the aforementioned libraries for being the inspiration & pathway for creating an entire new guideline for making the video caching possible in React Native. No wonder our React Native services is an unparalleled one! Hope you find it to be helpful to you & in case of any queries and suggestions, you can write to our mobile app development team. We’re all ears!