Install @candlefinance/faster-image
mainInstall the package using yarn:
yarn add @candlefinance/faster-imagerepository·main·Indexed 20 days ago
https://github.com/candlefinance/faster-imageA performant React Native library for image rendering optimized for speed and memory usage. It leverages Nuke on iOS/macOS and Coil on Android to provide advanced caching, placeholder support (blurhash, thumbhash, base64), and smooth transitions via the FasterImageView component. Includes utilities for prefetching images and clearing memory and disk caches.
Install the package using yarn:
yarn add @candlefinance/faster-imageThe FasterImageView component is the primary way to render images with optimized performance. It supports features like animated transitions, caching policies, and various placeholder types (blurhash, thumbhash, or base64).
import { FasterImageView } from '@candlefinance/faster-image';
<FasterImageView
style={styles.image}
onSuccess={(event) => {
console.log(event.nativeEvent);
}}
onError={(event) => console.warn(event.nativeEvent.error)}
source={{
transitionDuration: 0.3,
borderRadius: 50,
cachePolicy: 'discWithCacheControl',
showActivityIndicator: true,
url: 'https://picsum.photos/200/200?random=1',
}}
/>;Use clearCache() to clear both memory and disk caches used by the library.
import { clearCache } from '@candlefinance/faster-image';
await clearCache();Use prefetch to load images into the cache before they are needed in the UI. You can provide an array of URLs and optional headers.
import { prefetch } from '@candlefinance/faster-image';
// Basic prefetch
await prefetch(['https://picsum.photos/200/200?random=0']);
// Prefetch with headers
const token = 'your-token';
await prefetch(['https://picsum.photos/200/200?random=0'], {
headers: {
Authorization: `Bearer ${token}`,
},
});When using @candlefinance/faster-image in a React Native project where the package is located in a monorepo or a specific directory structure, you may need to configure react-native.config.js to ensure native assets and modules are correctly linked. Use the dependencies key to map the package name to its root directory using path.join.
const path = require('path');
const pak = require('../package.json');
module.exports = {
dependencies: {
[pak.name]: {
root: path.join(__dirname, '..'),
},
},
};When working with the FasterImageExample project, the metro.config.js is configured to prevent multiple versions of peer dependencies from being loaded. It achieves this by:
node_modules using resolver.blacklistRE.node_modules using resolver.extraNodeModules.This ensures that the bundler uses a single, consistent version of each peer dependency required by @candlefinance/faster-image.
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const path = require('path');
const escape = require('escape-string-regexp');
const exclusionList = require('metro-config/src/defaults/exclusionList');
const pak = require('../package.json');
const root = path.resolve(__dirname, '..');
const modules = Object.keys({ ...pak.peerDependencies });
const config = {
watchFolders: [root],
resolver: {
// Blocks peerDependencies at the root
blacklistRE: exclusionList(
modules.map(
(m) =>
new RegExp(`^${escape(path.join(root, 'node_modules', m))}\/.*$`)
)
),
// Aliases them to the versions in example's node_modules
extraNodeModules: modules.reduce((acc, name) => {
acc[name] = path.join(__dirname, 'node_modules', name);
return acc;
}, {}),
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
module.exports = mergeConfig(getDefaultConfig(__dirname), config);The following props are available for the FasterImageView component. Note that some props are platform-specific (iOS or Android only).
| Prop | Type | Default | Description |
| ------------------------- | --------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------- |
| url | string | | The URL of the image |
| style | object | | The style of the image |
| resizeMode | string | contain | The resize mode of the image |
| thumbhash | string | | The thumbhash of the image as a base64 encoded string to show while loading (Android not tested) |
| blurhash | string | | The blurhash of the image to show while loading (iOS only) |
| showActivityIndicator | boolean | false | Whether to show the UIActivityIndicatorView indicator when the image is loading (iOS only) |
| activityColor | ColorValue | undefined | Activity indicator color. Changed default activity indicator color. Only hex supported (iOS only) |
| base64Placeholder | string | | The base64 encoded placeholder image to show while the image is loading |
| cachePolicy | string | memory | The cache policy of the image |
| transitionDuration | number | 0.75 (iOS) 100 (Android) | The transition duration of the image |
| borderRadius | number | 0 | border radius of image |
| borderTopLeftRadius | number | 0 | top left border radius of image |
| borderTopRightRadius | number | 0 | top right border radius of image |
| borderBottomLeftRadius | number | 0 | bottom left border radius of image |
| borderBottomRightRadius | number | 0 | bottom right border radius of image |
| failureImage | string | | If the image fails to download this will be set (blurhash, thumbhash, base64) |
| progressiveLoadingEnabled | boolean | false | Progressively load images (iOS only) |
| onError | function | | The function to call when an error occurs. The error is passed as the first argument of the function |
| onSuccess | function | | The function to call when the image is successfully loaded |
| grayscale | number | 0 | Filter or transformation that converts the image into shades of gray (0-1). |
| colorMatrix | number[][] | | Color matrix that is applied to image |
| ignoreQueryParamsForCacheKey | boolean | false | Ignore URL query parameters in cache keys |
| allowHardware | boolean | true | Allow hardware rendering (Android only) |
| headers | Record<string, string> | undefined | Pass in headers |
| accessibilityLabel | string | undefined | accessibility label |
| accessible | boolean | undefined | is accessible |The FasterImageView component is the primary way to render high-performance images in React Native. It supports PNG and JPEG, and features like blurhash, base64 placeholders, and advanced caching. It is backed by the Nuke library on iOS.
To use it, provide a style and a source object containing the image url.
import { FasterImageView } from '@candlefinance/faster-image';
<FasterImageView
onSuccess={(event) => console.warn(event.nativeEvent.cacheKey)}
onError={(event) => console.warn(event.nativeEvent.error)}
style={{ width: 200, height: 200 }}}
source={{
transitionDuration: 0.3,
cachePolicy: 'discWithCacheControl',
showActivityIndicator: true,
failureImage: 'k0oGLQaSVsJ0BVhn2oq2Z5SQUQcZ',
url: 'https://picsum.photos/200/200?random=1',
}}
/>The FasterImageView component provides callbacks to monitor the loading lifecycle:
onSuccess: Triggered when the image loads successfully. The nativeEvent contains width, height, and source (which may include a cacheKey).onError: Triggered when an error occurs. The nativeEvent contains an error string.<FasterImageView
source={{ url: 'https://example.com/image.png' }}
onSuccess={(event) => {
const { width, height, source } = event.nativeEvent;
console.log('Loaded:', width, height, source);
}}
onError={(event) => {
console.error('Failed to load:', event.nativeEvent.error);
}}
/>The source prop of FasterImageView accepts an ImageOptions object.
Required Fields:
url: The string URL of the image.Common Optional Fields:
resizeMode: 'fill' | 'contain' | 'cover' | 'center' | 'top' | 'bottom' (Note: iOS supports more positions like topLeft, bottomRight, etc.)cachePolicy: 'memory' | 'discWithCacheControl' | 'discNoCacheControl' | 'memoryAndDisc'. Defaults to 'memory'.transitionDuration: Duration of the transition animation in seconds (defaults to 0.75).blurhash / thumbhash / base64Placeholder: Used for progressive loading or placeholder display.failureImage: Image to show when loading fails (can be a URL, blurhash, thumbhash, or base64).contentPosition: Position of the image content within the view (e.g., 'top', 'bottom', 'topLeft').priority: (iOS only) 'veryLow' | 'low' | 'normal' | 'high' | 'veryHigh'.showActivityIndicator: (iOS only) Shows a loading indicator, overriding placeholders.