Fast Speed Image Loading using React Native Fast Image

React Native Fast Image

Here is an example of Fast Speed Image Loading using React Native Fast Image in Android and IOS. React Native Fast Image library is really a cool library to load the image at a very fast speed. FastImage component from react-native-fast-image is a wrapper around SDWebImage (iOS) and Glide (Android) which are very powerful image loaders in native development.

React Native Fast Image provides a number of features to make your job easy like

  1. Aggressively cache images.
  2. Add authorization headers.
  3. Prioritize images.
  4. Preload images.
  5. GIF support.
  6. Border radius.

Different Properties of React Native FastImage

In the example, I have includes different ways and properties to load the image

1. Simple FastImage with source + header

<FastImage
  style={styles.image}
  source={{
    uri: 'https://unsplash.it/400/400?image=1',
    headers: { Authorization: '9876543210' },
  }}
/>

2. FastImage with different priority

<FastImage
    style={styles.image}
    source={{
    uri: 'https://unsplash.it/400/400?image=2',
    headers: { Authorization: '9876543210' },
    priority: FastImage.priority.low,
    //priority: FastImage.priority.normal,
    //priority: FastImage.priority.high,
    }}
/>

3. FastImage with different resizeMode

<FastImage
    style={styles.image}
    source={{
      uri: 'https://unsplash.it/400/400?image=5',
      headers: { Authorization: '9876543210' },
      priority: FastImage.priority.normal,
    }}
    resizeMode={FastImage.resizeMode.contain}
    //resizeMode={FastImage.resizeMode.cover}
    //resizeMode={FastImage.resizeMode.stretch}
    //resizeMode={FastImage.resizeMode.center}
/>
  • FastImage.resizeMode.contain – Scale the image uniformly (maintain the image’s aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).
  • FastImage.resizeMode.cover (Default) – Scale the image uniformly (maintain the image’s aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).
  • FastImage.resizeMode.stretch – Scale width and height independently, This may change the aspect ratio.
  • FastImage.resizeMode.center – Do not scale the image, keep centered.

4. FastImage with different Cache

<FastImage
  style={styles.image}
  source={{
    uri: 'https://unsplash.it/400/400?image=6',
    headers: { Authorization: '9876543210' },
    priority: FastImage.priority.normal,
    cache: FastImage.cacheControl.immutable,
    //cache: FastImage.cacheControl.web,
    //cache: FastImage.cacheControl.cacheOnly,
  }}
/>
  • FastImage.cacheControl.immutable – (Default) – Only updates if url changes.
  • FastImage.cacheControl.web – Use headers and follow normal caching procedures.
  • FastImage.cacheControl.cacheOnly – Only show images from the cache, do not make any network requests.

5. FastImage with Gif Support

<FastImage
    style={styles.image}
    source={{
      uri:
        'https://cdn-images-1.medium.com/max/1600/1*-CY5bU4OqiJRox7G00sftw.gif',
      headers: { Authorization: '9876543210' },
      priority: FastImage.priority.normal,
      cache: FastImage.cacheControl.immutable,
    }}
/>

6. Image Corner Radius Control

<FastImage
    style={{
      borderRadius: 50,
      borderTopLeftRadius: 10,
      borderBottomRightRadius: 10,
      height: 100,
      backgroundColor: '#ddd',
      margin: 20,
      flex: 1,
    }}
    source={{
      uri: 'https://unsplash.it/400/400?image=9',
    }}
/>

7. FastImage with Callback

<FastImage
    style={{ height: 100, width: 100 }}
    source={{
      uri: 'https://unsplash.it/400/400?image=9',
    }}
    onLoadStart={e => console.log('Loading Start')}
    onProgress={e =>
      console.log(
        'Loading Progress ' +
          e.nativeEvent.loaded / e.nativeEvent.total
      )
    }
    onLoad={e =>
      console.log(
        'Loading Loaded ' + e.nativeEvent.width,
        e.nativeEvent.height
      )
    }
    onLoadEnd={e => console.log('Loading Ended')}
/>

Now you can understand how useful is this library. So let’s see the coding part.

In this example, we will cover almost all the properties mentioned above and will create a floating action button to switch to the image grid which has many images and will help us to test the capabilities of the FastImage Library.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To use FastImage component we need to install react-native-fast-image dependency.

To install these dependencies open the terminal and jump into your project using

cd ProjectName

Run the following commands

npm install react-native-fast-image --save

This command will copy all the dependencies into your node_module directory.

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install

Code

Now open App.js in any code editor and replace the code with the following code

App.js

// Fast Speed Image Loading using React Native Fast Image
// https://aboutreact.com/react-native-fast-image/

// import React in our code
import React, {useState, useEffect} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  Image,
  FlatList,
} from 'react-native';

import FastImage from 'react-native-fast-image';

const App = () => {
  const [showGrid, setShowGrid] = useState(false);
  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    let items = Array.apply(null, Array(60)).map((v, i) => {
      return {
        id: i,
        src: 'https://unsplash.it/400/400?image=' + (i + 1)
      };
    });
    setDataSource(items);
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        {!showGrid ? (
          <ScrollView style={{flex: 1}}>
            <View style={styles.container}>
              <Text style={styles.titleStyle}>
                Example of React native Fast Image
              </Text>

              <View
                style={{
                  padding: 16,
                  flexDirection: 'row',
                  marginTop: 20
                }}>
                <FastImage
                  style={styles.imageStyle}
                  source={{
                    uri: 'https://unsplash.it/400/400?image=1',
                    headers: {Authorization: '9876543210'},
                  }}
                />
                <Text style={{flex: 1, textAlign: 'center'}}>
                  Simple FastImage {'\n'} source + header
                </Text>
              </View>

              <View
                style={{
                  padding: 16,
                  flexDirection: 'column',
                  marginTop: 20
                }}>
                <Text style={{textAlign: 'center'}}>
                  Different FastImage with different priority
                </Text>
                <View
                  style={{
                    flexDirection: 'row',
                    marginTop: 20,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}>
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=2',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.low,
                    }}
                  />
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=3',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.normal,
                    }}
                  />
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=4',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.high,
                    }}
                  />
                </View>
              </View>

              <View
                style={{
                  padding: 16,
                  flexDirection: 'column',
                  marginTop: 20
                }}>
                <Text style={{textAlign: 'center'}}>
                  Different FastImage with different resizeMode
                </Text>
                <View
                  style={{
                    flexDirection: 'row',
                    marginTop: 20,
                    justifyContent: 'center',
                  }}>
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=5',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.normal,
                    }}
                    resizeMode={FastImage.resizeMode.contain}
                  />
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=5',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.normal,
                    }}
                    resizeMode={FastImage.resizeMode.cover}
                  />
                </View>
                <View
                  style={{
                    flexDirection: 'row',
                    marginTop: 10,
                    justifyContent: 'center',
                  }}>
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=5',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.normal,
                    }}
                    resizeMode={FastImage.resizeMode.cover}
                  />
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=5',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.normal,
                    }}
                    resizeMode={FastImage.resizeMode.center}
                  />
                </View>
              </View>
              <View
                style={{
                  padding: 16,
                  flexDirection: 'column',
                  marginTop: 20,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Text style={{textAlign: 'center'}}>
                  Different FastImage with different Cache
                </Text>
                <View
                  style={{
                    flexDirection: 'row',
                    marginTop: 20,
                    justifyContent: 'center',
                  }}>
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=6',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.normal,
                      cache: FastImage.cacheControl.immutable,
                    }}
                  />
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=7',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.normal,
                      cache: FastImage.cacheControl.web,
                    }}
                  />
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=8',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.normal,
                      cache: FastImage.cacheControl.cacheOnly,
                    }}
                  />
                </View>
              </View>
              <View
                style={{
                  padding: 16,
                  flexDirection: 'column',
                  marginTop: 20,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Text style={{textAlign: 'center'}}>
                  Gif Support in React Native
                </Text>
                <View style={{flexDirection: 'row', marginTop: 20}}>
                  <FastImage
                    style={styles.imageStyle}
                    source={{
                      uri:
                        'https://cdn-images-1.medium.com/max/1600/1*-CY5bU4OqiJRox7G00sftw.gif',
                      headers: {Authorization: '9876543210'},
                      priority: FastImage.priority.normal,
                      cache: FastImage.cacheControl.immutable,
                    }}
                  />
                </View>
              </View>
              <View
                style={{
                  padding: 16,
                  flexDirection: 'column',
                  marginTop: 20,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Text style={{textAlign: 'center'}}>
                  Controll the Corner Radius of Image
                </Text>
                <View style={{flexDirection: 'row', marginTop: 20}}>
                  <FastImage
                    style={{
                      borderRadius: 50,
                      height: 100,
                      backgroundColor: '#ddd',
                      margin: 20,
                      width: 100,
                      flex: 0,
                    }}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=9',
                    }}
                  />
                  <FastImage
                    style={{
                      borderRadius: 50,
                      borderTopLeftRadius: 10,
                      borderBottomRightRadius: 10,
                      height: 100,
                      backgroundColor: '#ddd',
                      margin: 20,
                      flex: 1,
                    }}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=9',
                    }}
                  />
                </View>
              </View>
              <View
                style={{
                  padding: 16,
                  flexDirection: 'column',
                  marginTop: 20,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Text style={{textAlign: 'center'}}>
                  Fast Image with Callback
                </Text>
                <View
                  style={{
                    flexDirection: 'row',
                    marginTop: 20,
                    justifyContent: 'center',
                  }}>
                  <FastImage
                    style={{height: 100, width: 100}}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=9',
                    }}
                    onLoadStart={(e) => console.log('Loading Start')}
                    onProgress={(e) =>
                      console.log(
                        'Loading Progress ' +
                          e.nativeEvent.loaded / e.nativeEvent.total,
                      )
                    }
                    onLoad={(e) =>
                      console.log(
                        'Loading Loaded ' + e.nativeEvent.width,
                        e.nativeEvent.height,
                      )
                    }
                    onLoadEnd={(e) => console.log('Loading Ended')}
                  />
                </View>
              </View>
            </View>
          </ScrollView>
        ) : (
          <View style={{flex: 1}}>
            <FlatList
              data={dataSource}
              renderItem={({item}) => (
                <View
                  style={{
                    flex: 1,
                    flexDirection: 'column',
                    margin: 1
                  }}>
                  <FastImage
                    style={styles.imageThumbnailStyle}
                    source={{
                      uri: item.src,
                      priority: FastImage.priority.high,
                    }}
                  />
                </View>
              )}
              //Setting the number of column
              numColumns={3}
              keyExtractor={(item, index) => index}
            />
          </View>
        )}
        <TouchableOpacity
          activeOpacity={0.7}
          onPress={() => setShowGrid(!showGrid)}
          style={styles.touchableOpacityStyle}>
          <Image
            source={{
              uri:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/plus_icon.png',
            }}
            style={styles.floatingButtonStyle}
          />
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};
export default App;
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    marginTop: 30,
  },
  titleStyle: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  imageStyle: {
    height: 70,
    width: 100,
    marginRight: 10,
  },
  touchableOpacityStyle: {
    position: 'absolute',
    width: 50,
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
    right: 30,
    bottom: 30,
  },
  imageThumbnailStyle: {
    justifyContent: 'center',
    alignItems: 'center',
    height: 100,
  },
  floatingButtonStyle: {
    resizeMode: 'contain',
    width: 50,
    height: 50,
    //backgroundColor:'black'
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device:

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Output Screenshots

Android

       

IOS

This is how you can load the image with lightning speed using React Native Fast Image. If you have any doubts or want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

2 thoughts on “Fast Speed Image Loading using React Native Fast Image”

    • Hello, You can use Style to make a placeholder like I have applied background.
      style={{ borderRadius: 50, height: 100, backgroundColor: ‘#ddd’, margin: 20, width: 100, flex: 0, }}

      By the way, it is loading very fast at the client-side you have to check your server performance.

      Reply

Leave a Comment

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