Preload Images in React Native – Android & IOS

It’s a common requirement in the Apps to load images from remote URLs. React Native Image component automatically keeps images in the cache for future use and fast loading. But the very first time it can take time to download an image from a remote URL. Sometimes it looks weird when the image comes after a few seconds and it affects user experience. Here its described how to Preload Images in React Native.

You can use the following method to Prefetch images before actually showing it to the user. Usually, we can call this function at the start of the App to download Images and keep in cache. So that it should be loaded fast when it is actually required to populate in React Native Image component.

Method to Preload Images In React Native

preloadImages(urlOfImages) { // an array of urls of images
     let preFetchTasks = [];
     urlOfImages.forEach((url)=>{
        preFetchTasks.push(Image.prefetch(url));
    });

    Promise.all(preFetchTasks).then((results)=>{
    try {
      let downloadedAll = true;
      results.forEach((result)=>{
          if(!result){
              //error occurred downloading a pic
              downloadedAll = false;
          }
      })
    }catch(e){}
})

}

How to Use preloadImages() method?

var urlOfImages = [];
urlOfImages.push("image_1_url"); // Replace it with your actual URL
urlOfImages.push("image_2_url");
preloadImages(urlOfImages);

This method downloads images and saves it in the cache. Now you can load Your images in React Native Image component with URL, as you normally do. And it should be loaded fast from the cache.

Load image in Image component from remote URL

<Image source={{uri: "image_1_url"}} style={{width: 30, height: 30}} resizeMode="stretch" />

Enjoy ๐Ÿ™‚ You can use this method for both Android & IOS.

You can find other helping articles and coding solutions here.

Next:

1. Run React Native App on a Specific Device or Simulator

2. Fetch Nearest Places in React Native

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

One thought on “Preload Images in React Native – Android & IOS

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: