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 the 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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

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

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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 dependency into your node_module directory.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods. So to install pods use

cd ios && pod install && cd ..

Code

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

App.js

/*Example of React Native Fast Image*/
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  Image,
  FlatList,
} from 'react-native';
import FastImage from 'react-native-fast-image';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = { showGrid: false };
  }
  clickHandler() {
    alert(this.state.showGrid);
    //this.setState({showGrid:!this.state.showGrid});
  }
  componentDidMount() {
    var that = this;
    let items = Array.apply(null, Array(60)).map((v, i) => {
      return { id: i, src: 'https://unsplash.it/400/400?image=' + (i + 1) };
    });
    that.setState({
      dataSource: items,
    });
  }
  render() {
    return (
      <View style={{ flex: 1 }}>
        {!this.state.showGrid ? (
          <ScrollView style={{ flex: 1 }}>
            <View style={styles.container}>
              <Text style={styles.textLarge}>
                Example of React native Fast Image
              </Text>

              <View
                style={{ padding: 16, flexDirection: 'row', marginTop: 20 }}>
                <FastImage
                  style={styles.image}
                  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.image}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=2',
                      headers: { Authorization: '9876543210' },
                      priority: FastImage.priority.low,
                    }}
                  />
                  <FastImage
                    style={styles.image}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=3',
                      headers: { Authorization: '9876543210' },
                      priority: FastImage.priority.normal,
                    }}
                  />
                  <FastImage
                    style={styles.image}
                    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.image}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=5',
                      headers: { Authorization: '9876543210' },
                      priority: FastImage.priority.normal,
                    }}
                    resizeMode={FastImage.resizeMode.contain}
                  />
                  <FastImage
                    style={styles.image}
                    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.image}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=5',
                      headers: { Authorization: '9876543210' },
                      priority: FastImage.priority.normal,
                    }}
                    resizeMode={FastImage.resizeMode.cover}
                  />
                  <FastImage
                    style={styles.image}
                    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.image}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=6',
                      headers: { Authorization: '9876543210' },
                      priority: FastImage.priority.normal,
                      cache: FastImage.cacheControl.immutable,
                    }}
                  />
                  <FastImage
                    style={styles.image}
                    source={{
                      uri: 'https://unsplash.it/400/400?image=7',
                      headers: { Authorization: '9876543210' },
                      priority: FastImage.priority.normal,
                      cache: FastImage.cacheControl.web,
                    }}
                  />
                  <FastImage
                    style={styles.image}
                    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.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,
                    }}
                  />
                </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={this.state.dataSource}
              renderItem={({ item }) => (
                <View style={{ flex: 1, flexDirection: 'column', margin: 1 }}>
                  <FastImage
                    style={styles.imageThumbnail}
                    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={() => this.setState({ showGrid: !this.state.showGrid })}
          style={styles.TouchableOpacityStyle}>
          <Image
            source={{
              uri:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/plus_icon.png',
            }}
            style={styles.FloatingButtonStyle}
          />
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    marginTop: 30,
  },
  textLarge: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  image: {
    height: 70,
    width: 100,
    marginRight: 10,
  },
  TouchableOpacityStyle: {
    position: 'absolute',
    width: 50,
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
    right: 30,
    bottom: 30,
  },
  imageThumbnail: {
    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
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

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 you 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. 🙂


Related Posts

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.