Efficient Video Caching in React Native CLI with React Native Video: A Complete Guide 2024

In today’s world of mobile apps, video streaming is one of the core features for boosting user engagement with the application. Whether it’s a video-sharing platform, an educational app, or a multimedia-rich social network, providing a seamless video playback experience is crucial.

To deliver this experience, we require a solid grasp of video caching as effective caching doesn’t just improve load times; it ensures uninterrupted streaming, reduces buffering, and optimizes data usage.

This guide will go through all the required steps to install, configure, and use react-native-video to create a smooth video streaming experience in your React Native CLI applications.

Installation

First, we need to install the react-native-video and react-native-video-cache libraries in the React Native project.

#using npm npm install react-native-video react-native-video-cache #using yarn yarn add react-native-video react-native-video-cache

For iOS apps, we require one more step i.e install the required pod files,

#enter the command in the root directory of the project cd ios pod install

Native setup for Video caching

For Android and iOS, the setup will be different as we have to apply changes to the native files for the video caching to work properly.

Android:

Go to build.gradle file inside the android folder of your react native cli project and add the below snippet.

buildscript { ext { // Other configurations // Enable IMA (Interactive Media Ads) integration with ExoPlayer useExoplayerIMA = false // Enable support for RTSP (Real-Time Streaming Protocol) with ExoPlayer useExoplayerRtsp = true // Enable support for Smooth Streaming with ExoPlayer useExoplayerSmoothStreaming = true // Enable support for DASH (Dynamic Adaptive Streaming over HTTP) with ExoPlayer useExoplayerDash = true // Enable support for HLS (HTTP Live Streaming) with ExoPlayer useExoplayerHls = true } } allprojects { repositories { maven { url "$rootDir/../node_modules/react-native-video-cache/android/libs" } } }

This configuration enables various streaming protocols in ExoPlayer and sets up repositories to include a custom Maven repository for react-native-video-cache.

Each of these features enabled will increase the size of your APK, so only enable the features you need. Default required enabled features are: useExoplayerSmoothStreaming, useExoplayerDash, useExoplayerHls.

Now lets go to the AndroidManifest.xml file and include the given parameters,

<application ... android:largeHeap="true" android:hardwareAccelerated="true">

This ensures that the app has enough memory to handle large datasets (via largeHeap) and can render graphics efficiently (via hardwareAccelerated), leading to a smoother and more stable video streaming experience with video caching.

Now lets go to build.gradle inside the app folder inside android folder. So the final path should be project_path/android/app/build.gradle

dependencies { ... //add these dependencies implementation('com.danikula:videocache:2.7.1') implementation("org.slf4j:slf4j-api:2.0.9") }

IOS:

For iOS app, lets go to ios/Podfile file

... # -- ENABLE THIS FOR CACHEING THE VIDEOS $RNVideoUseVideoCaching=true ... target 'your_app' do ... # ENABLE THIS FOR CACHEING THE VIDEOS pod 'SPTPersistentCache', :modular_headers => true; pod 'DVAssetLoaderDelegate', :modular_headers => true; ...

It enables video caching in the iOS app by adding specific CocoaPods (SPTPersistentCache and DVAssetLoaderDelegate) that handle caching and asset loading. The flag $RNVideoUseVideoCaching=true signals that the project should use these caching capabilities.

Implementation in React Native

Now that we have implemented the native file changes for both android and ios, now its time to implement the video caching in the react native code using react-native-video.

Lets go to the video component in which you are going to show the video.

In videoComponent file

#import the modules import Video from 'react-native-video'; import convertToProxyURL from 'react-native-video-cache'; <Video // Display a thumbnail image while the video is loading poster={video?.thumbUri} // Specifies how the thumbnail should be resized to cover the entire video area posterResizeMode="cover" // Sets the video source URI if the video is visible; otherwise, it avoids loading the video source={ isVisible ? { uri: convertToProxyURL(video?.videoUri) } // Converts the video URL to a proxy URL if visible : undefined // Avoid loading the video if not visible } // Configures buffer settings to manage video loading and playback bufferConfig={{ minBufferMs: 2500, // Minimum buffer before playback starts maxBufferMs: 3000, // Maximum buffer allowed bufferForPlaybackMs: 2500, // Buffer required to start playback bufferForPlaybackAfterRebufferMs: 2500, // Buffer required after rebuffering }} // Ignores the silent switch on the device, allowing the video to play with sound even if the device is on silent mode ignoreSilentSwitch={'ignore'} // Prevents the video from playing when the app is inactive or in the background playWhenInactive={false} playInBackground={false} // Disables the use of TextureView, which can optimize performance but might limit certain effects useTextureView={false} // Hides the default media controls provided by the video player controls={false} // Disables focus on the video, which is useful for accessibility and UI focus management disableFocus={true} // Applies the defined styles to the video container style={styles.videoContainer} // Pauses the video based on the isPaused state paused={isPaused} // Repeats the video playback indefinitely repeat={true} // Hides the shutter view (a black screen that appears when the video is loading or paused) hideShutterView // Sets the minimum number of retry attempts when the video fails to load minLoadRetryCount={5} // Ensures the video maintains the correct aspect ratio by covering the entire view area resizeMode="cover" // Sets the shutter color to transparent, so the shutter view is invisible shutterColor="transparent" />

Now, your video component will stream the video more smoothly and stable, enhancing the user experience with low data consumption due to video caching.

Optimization Tips

Even with video caching, sometimes it is not sufficient to get a smooth video playback experience, so to further optimize the user experience, you can follow the below suggestions:

  • CDN: Use a CDN (Content Delivery Network) to host your videos, which will lead to faster loading of the videos.
  • Adaptive Streaming: Implement adaptive streaming (HLS or DASH) to get optimized video quality based on the user network conditions.
  • Optimize Video Files: You can use different compressing tools to compress the video file without losing the video quality, resulting in a smaller video file that can reduce the load time.

By effectively implementing video caching, we can minimize loading times, reduce buffering, and keep the app responsive, even in low-bandwidth environments.

This optimization not only enhances playback performance but also conserves users’ data and improves their overall satisfaction with the app.