React Native Image Cache
CachedImage component and Cache image manager for React Native. Here are several articles on RN and image processing:
Installation
npm install react-native-img-cache --save
react-native-fetch-blob
This package has a dependency with react-native-fetch-blob.
If your project doesn't have a dependency with this package already, please refer to their installation instructions.
Usage
CachedImage
The CachedImage
component assumes that the image URI will never change. The image is stored and served from the application cache.
import {CachedImage} from "react-native-img-cache";
<CachedImage source={{ uri: "https://i.ytimg.com/vi/yaqe1qesQ8c/maxresdefault.jpg" }} />
The mutable
property implies assumes that the image URI can change over time. The lifetime of this cache is the one of the running application and it can be manually busted using ImageCache
.
import {CachedImage} from "react-native-img-cache";
<CachedImage source={{ uri: "https://i.ytimg.com/vi/yaqe1qesQ8c/maxresdefault.jpg" }} mutable />
ImageCache
clear()
Remove cache entries and all physical files.
ImageCache.get().clear();
bust(uri)
ImageCache
can be used to bust an image from the local cache.
This removes the cache entry but it does not remove any physical files.
ImageCache.get().bust("https://i.ytimg.com/vi/yaqe1qesQ8c/maxresdefault.jpg");
cancel(uri)
It can also be used to cancel the download of an image. This can be very useful when scrolling through images.
ImageCache.get().cancel("https://i.ytimg.com/vi/yaqe1qesQ8c/maxresdefault.jpg");
on(uri, observer, immutable)
The ImageCache
class can register observers to the cache.
const immutable = true;
const observer = (path: string) => {
console.log(`path of the image in the cache: ${path}`);
};
ImageCache.get().on(uri, observer, immutable);
We use the observer pattern instead of a promise because a mutable image might have different version with different paths in the cache.
dispose(uri, observer)
Observers can be deregistered using dispose
:
ImageCache.get().dispose(uri, observer);