13
votes

I read the document about the React Native image component in this site and got some questions: https://facebook.github.io/react-native/docs/image.html

  1. If I use the source property to display image. Will the image be cached and save to disk after download?

  2. If yes, what is the cache policy?

  3. If I want to save the downloaded image to disk. Is it better to use getSize or prefetch method to do it?

Many thanks.

4

4 Answers

4
votes

React native image component NSURLRequest's cache policy as described here. Personally I use RNFetchBlob to cache images as described here. You can also checkout this component.

2
votes

You may be interested in my higher order component module that adds performance related image caching and "permanent cache" functionality to the native <Image> component.

React Native Image Cache HOC

Tl;DR Code Example:

import imageCacheHoc from 'react-native-image-cache-hoc';
const CacheableImage = imageCacheHoc(Image);

export default class App extends Component<{}> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <CacheableImage style={styles.image} source={{uri: 'https://i.redd.it/rc29s4bz61uz.png'}} />
        <CacheableImage style={styles.image} source={{uri: 'https://i.redd.it/hhhim0kc5swz.jpg'}} permanent={true} />
      </View>
  );
  }
}

The first image will be cached until the total local cache grows past 15 MB (by default) then cached images are deleted oldest first until total cache is below 15 MB again.

The second image will be stored to local disk permanently. People use this as a drop in replacement for shipping static image files with your app.

That should handle your requirement out of the box. Hope it helps!

2
votes

FastImage is best for Image Cache

yarn add react-native-fast-image

Ref: https://github.com/DylanVann/react-native-fast-image

Its maximum props behave like as React native image attribute

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


<FastImage
    style={{ width: 200, height: 200 }}
    source={{ uri: 'https://unsplash.it/400/400?image=1' }}
    resizeMode={FastImage.resizeMode.stretch}

/>
1
votes

Process

React Native does cache images after downloading and decoding them. enter image description here

Cache policy

  1. expiration time

2.using Bitmap size as cache cost; by default, total 20MB cache capacity in React Native iOS

  1. unknown storage and eviction policy in NSCache in iOS

see more in How Image Loader and Cache work in React Native under the hood