### Install and Link Dependencies Source: https://github.com/dylanvann/react-native-fast-image/blob/main/docs/development.md Follow these steps to install dependencies, link the module, and start the example app for development. Ensure you are in the repo root folder before starting. ```bash yarn yarn link cd ReactNativeFastImageExample yarn yarn link react-native-fast-image yarn start ``` ```bash yarn react-native run-ios yarn react-native run-android ``` -------------------------------- ### Complete Image Loading Example with Callbacks Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/events-and-callbacks.md This example demonstrates how to use all available FastImage callbacks to manage loading states, display progress, handle errors, and record image dimensions and load times. ```typescript import React, { useState, useRef } from 'react' import { View, Text, ActivityIndicator, TouchableOpacity } from 'react-native' import FastImage from 'react-native-fast-image' interface ImageLoadState { isLoading: boolean progress: number hasError: boolean dimensions: { width: number; height: number } | null loadTime: number | null } export default function ImageWithMetrics({ uri }: { uri: string }) { const [state, setState] = useState({ isLoading: false, progress: 0, hasError: false, dimensions: null, loadTime: null }) const startTime = useRef(0) const handleLoadStart = () => { startTime.current = Date.now() setState(prev => ({ ...prev, isLoading: true, hasError: false, progress: 0 })) } const handleProgress = (event: any) => { const progress = event.nativeEvent.loaded / event.nativeEvent.total setState(prev => ({ ...prev, progress })) } const handleLoad = (event: any) => { const { width, height } = event.nativeEvent const loadTime = Date.now() - startTime.current setState(prev => ({ ...prev, dimensions: { width, height }, loadTime })) } const handleError = () => { setState(prev => ({ ...prev, hasError: true })) } const handleLoadEnd = () => { setState(prev => ({ ...prev, isLoading: false })) } const handleRetry = () => { setState({ isLoading: false, progress: 0, hasError: false, dimensions: null, loadTime: null }) } return ( {state.hasError ? ( Failed to load image Retry ) : ( {state.isLoading && ( {Math.round(state.progress * 100)}% )} {state.dimensions && ( Dimensions: {state.dimensions.width}x{state.dimensions.height} {state.loadTime && Load time: {state.loadTime}ms} )} )} ) } ``` -------------------------------- ### Complete FastImage Usage Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/fastimage-component.md A comprehensive example demonstrating how to use FastImage with various props, including source configuration with headers and priority, caching, resize mode, default source, and event handlers for loading, progress, errors, and completion. ```typescript import React, { useState } from 'react' import { View, Text } from 'react-native' import FastImage from 'react-native-fast-image' export default function ImageGalleryItem({ imageUrl, authToken }) { const [dimensions, setDimensions] = useState(null) const [progress, setProgress] = useState(0) const [isLoading, setIsLoading] = useState(false) const [hasError, setHasError] = useState(false) return ( {isLoading && Loading...} {hasError && Failed to load image} setIsLoading(true)} onProgress={(e) => { const prog = e.nativeEvent.loaded / e.nativeEvent.total setProgress(prog) }} onLoad={(e) => { setIsLoading(false) setDimensions(e.nativeEvent) }} onError={() => { setIsLoading(false) setHasError(true) }} onLoadEnd={() => setIsLoading(false)} /> {dimensions && ( Image size: {dimensions.width}x{dimensions.height} )} {progress > 0 && Progress: {Math.round(progress * 100)}%} ) } ``` -------------------------------- ### Install React Native FastImage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/README.md Install the library using Yarn and then run pod install for iOS dependencies. Ensure you are using React Native 0.60.0 or higher. ```bash yarn add react-native-fast-image cd ios && pod install ``` -------------------------------- ### onLoadStart Callback Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/events-and-callbacks.md Use onLoadStart to set a loading state when an image begins to download. This callback fires before any progress updates. ```typescript const [isLoading, setIsLoading] = useState(false) { setIsLoading(true) console.log('Starting to load image') }} /> ``` -------------------------------- ### Image Loading Priority Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/types.md Example of setting a high priority for an image request using FastImage. Ensure FastImage is imported. ```typescript import FastImage from 'react-native-fast-image' ``` -------------------------------- ### OnLoad Event Handling Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/types.md Example of handling the onLoad event to log the dimensions of a loaded image. The width and height are accessed via event.nativeEvent. ```typescript { const { width, height } = event.nativeEvent console.log(`Loaded: ${width}x${height}`) }} /> ``` -------------------------------- ### High Priority Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Demonstrates using 'high' priority for a featured image and 'normal' priority for a thumbnail within a View component. ```typescript {/* Featured image - high priority */} {/* Article thumbnail - normal priority */} ``` -------------------------------- ### Successful Image Load Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/README.md This snippet demonstrates the `onLoad` prop, which is called upon a successful image fetch. It provides the width and height of the loaded image. ```jsx onLoad={e => console.log(e.nativeEvent.width, e.nativeEvent.height)} ``` -------------------------------- ### Image Cache Control Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/types.md Example of using the 'cacheOnly' strategy to load an image solely from the cache. Import FastImage and set the cache property in the source object. ```typescript import FastImage from 'react-native-fast-image' ``` -------------------------------- ### Tracking Image Load Analytics with onLoadEnd Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/events-and-callbacks.md Utilize onLoadEnd to send image loading metrics to an analytics service. This example tracks the start time, end time, and status (success/error) of image loads. ```typescript const [loadMetrics, setLoadMetrics] = useState({ startTime: 0, endTime: undefined, status: 'loading' as 'loading' | 'success' | 'error' } | null>(null)) const handleLoadStart = () => { setLoadMetrics({ startTime: Date.now(), status: 'loading' }) } const handleLoad = () => { setLoadMetrics(prev => prev ? { ...prev, status: 'success' } : null) } const handleError = () => { setLoadMetrics(prev => prev ? { ...prev, status: 'error' } : null) } const handleLoadEnd = () => { setLoadMetrics(prev => { if (prev) { const metric = { ...prev, endTime: Date.now() } analytics.track('image_load_complete', metric) return metric } return prev }) } ``` -------------------------------- ### Image Loading Progress Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/README.md This snippet shows how to use the `onProgress` prop to log the loading progress of an image. The progress is calculated as loaded bytes divided by total bytes. ```jsx onProgress={e => console.log(e.nativeEvent.loaded / e.nativeEvent.total)} ``` -------------------------------- ### FastImage Source Configuration with All Options Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/fastimage-component.md Configure the `source` prop with URI, custom HTTP headers, loading priority, and cache control behavior. This example demonstrates setting a high priority and using web cache control. ```typescript ``` -------------------------------- ### Normal Priority Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Shows how to use FastImage without specifying a priority, which defaults to 'normal'. ```typescript ``` -------------------------------- ### Configure Images in a Gallery with FastImage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/configuration.md Example of configuring FastImage within a `FlatList` for a gallery view. Includes setting image source with optional authentication headers, priority, cache control, and styling. Also demonstrates preloading the next batch of images. ```typescript import React, { useCallback } from 'react' import { FlatList, View } from 'react-native' import FastImage from 'react-native-fast-image' interface ImageItem { id: string uri: string authToken?: string } export default function GalleryScreen({ images }: { images: ImageItem[] }) { const renderImage = useCallback(({ item }: { item: ImageItem }) => ( ), []) return ( item.id} onEndReachedThreshold={0.5} onEndReached={() => { // Preload next batch of images const nextBatch = images.slice(-10) FastImage.preload(nextBatch.map(img => ({ uri: img.uri, headers: img.authToken ? { Authorization: `Bearer ${img.authToken}` } : {} }))) }} /> ) } ``` -------------------------------- ### Server Headers Example for Web Cache Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Illustrates HTTP headers that control caching behavior for the 'web' cache mode. These headers are set by the server to manage image freshness and cache duration. ```text Cache-Control: public, max-age=3600 // Cache for 1 hour Cache-Control: public, max-age=86400 // Cache for 1 day Cache-Control: no-cache // Validate before using ETag: "33a64df54425425" // Resource version identifier Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT ``` -------------------------------- ### Low Priority Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Illustrates using the 'low' priority for images in a FlatList, setting the first item to high priority and the rest to low. ```typescript // List view with images ( )} /> ``` -------------------------------- ### FastImage Component Usage with Progress Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/types.md Example of using the FastImage component with the onProgress callback to display download progress. Ensure the OnProgressEvent type is imported. ```typescript { const progress = event.nativeEvent.loaded / event.nativeEvent.total console.log(`Progress: ${Math.round(progress * 100)}%`) }} /> ``` -------------------------------- ### Web Cache Control Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Employ the 'web' cache mode to respect standard HTTP cache headers like 'Cache-Control', 'ETag', and 'Last-Modified'. This mode balances freshness with performance for dynamic content. ```typescript // User profile - server controls freshness // Blog post image with server cache headers ``` -------------------------------- ### iOS Event Flow Sequence Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/architecture.md Illustrates the sequence of events from initiating an image reload to handling load start, progress, success, and error callbacks on iOS. ```text reloadImage() [sync] │ ├─ onFastImageLoadStart (sync) │ └─ sd_setImageWithURL [async] │ ├─ onProgress [multiple, from SDWebImage] │ └─ Swift → native event → RN JS │ ├─ Success Path: │ └─ sendOnLoad() → onFastImageLoad │ └─ onFastImageLoadEnd │ └─ Error Path: └─ onFastImageError └─ onFastImageLoadEnd ``` -------------------------------- ### onProgress Callback for Download Speed Calculation Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/events-and-callbacks.md Utilize onProgress to calculate and log download speed. This requires tracking the start time and the last reported downloaded size to compute the rate. ```typescript const downloadStartTime = useRef(0) const lastReportedSize = useRef(0) const handleProgress = (event: OnProgressEvent) => { const { loaded, total } = event.nativeEvent const elapsedSeconds = (Date.now() - downloadStartTime.current) / 1000 const bytesDownloadedThisUpdate = loaded - lastReportedSize.current const speedMbps = (bytesDownloadedThisUpdate / 1024 / 1024) / elapsedSeconds console.log(`Speed: ${speedMbps.toFixed(2)} MB/s`) lastReportedSize.current = loaded } { downloadStartTime.current = Date.now() lastReportedSize.current = 0 }} onProgress={handleProgress} /> ``` -------------------------------- ### Measuring Image Load Time with onLoadEnd Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/events-and-callbacks.md Record the time taken for an image to load by capturing the start time in onLoadStart and calculating the duration in onLoadEnd. This is useful for performance analysis. ```typescript const loadStartTime = useRef(0) const handleLoadStart = () => { loadStartTime.current = Date.now() } const handleLoadEnd = () => { const loadTime = Date.now() - loadStartTime.current console.log(`Load time: ${loadTime}ms`) } ``` -------------------------------- ### FastImage Component Usage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/README.md Example of how to use the FastImage component in a React Native application, including setting the source, style, and resize mode. ```APIDOC ## FastImage Component ### Description A React Native component for displaying images with enhanced performance and caching capabilities. ### Usage ```jsx import FastImage from 'react-native-fast-image' const YourImage = () => ( ) ``` ### Properties - **source**: `object` - Source for the remote image to load. - **uri**: `string` - Remote url to load the image from. - **headers**: `object` - Headers to load the image with. - **priority**: `enum` - Priority for loading the image (`low`, `normal`, `high`). Defaults to `normal`. - **cache**: `enum` - Cache control for the image (`immutable`, `web`, `cacheOnly`). Defaults to `immutable`. - **defaultSource**: `number` - An asset loaded with `require(...)`. - **resizeMode**: `enum` - How to resize the image (`contain`, `cover`, `stretch`, `center`). Defaults to `cover`. - **onLoadStart**: `() => void` - Called when the image starts to load. - **onProgress**: `(event) => void` - Called when the image is loading. - **onLoad**: `(event) => void` - Called on a successful image fetch. - **onError**: `() => void` - Called on an image fetching error. - **onLoadEnd**: `() => void` - Called when the image finishes loading. - **style**: `object` - A React Native style. Supports using `borderRadius`. - **fallback**: `boolean` - If true will fallback to using `Image`. - **tintColor**: `number | string` - If supplied, changes the color of all the non-transparent pixels to the given color. ``` -------------------------------- ### Immutable Cache Control Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Use the 'immutable' cache mode for assets where the URI is guaranteed to be static and unchanging. This provides the fastest caching by skipping all network validation. ```typescript // Versioned asset - immutable // Avatar with hash in URL ``` -------------------------------- ### onLoadStart Callback Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/events-and-callbacks.md This callback is invoked when the image begins its loading process. It's useful for initiating loading indicators or resetting state. ```APIDOC ## onLoadStart ### Description Called when the image starts loading. ### Signature ```typescript onLoadStart?(): void ``` ### When triggered: - Immediately after source prop is set - When image URL changes - When component mounts with a valid source ### Behavior: - Called synchronously or near-synchronously - No arguments passed - Always fires before onProgress ### Use cases: - Show loading indicator - Reset previous state - Start timing operations ### Example: ```typescript const [isLoading, setIsLoading] = useState(false) { setIsLoading(true) console.log('Starting to load image') }} /> ``` ### Timing: - iOS: Called when SDWebImage starts download - Android: Called when Glide begins loading ``` -------------------------------- ### Basic Source Configuration Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/configuration.md Configure image loading and caching using the `source` prop. Include URI, optional headers, priority, and cache strategy. ```typescript ``` -------------------------------- ### Image Loading with All Options Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/README.md Demonstrates loading an image with all available options, including priority, cache control, fallback sources, and various event handlers. ```typescript console.log('Loading...')} onProgress={(e) => console.log(e.nativeEvent.loaded / e.nativeEvent.total)} onLoad={(e) => console.log(`Image: ${e.nativeEvent.width}x${e.nativeEvent.height}`)} onError={() => console.log('Load failed')} onLoadEnd={() => console.log('Done')} /> ``` -------------------------------- ### Accessing FastImage Ref Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/fastimage-component.md Demonstrates how to use `useRef` to get a reference to the FastImage component, providing access to its underlying View. ```typescript const imageRef = useRef(null) ``` -------------------------------- ### Get Priority Conditionally Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Determines the FastImage priority based on visibility and featured status. Use this to manage image loading priorities. ```typescript const getPriority = (isVisible: boolean, isFeatured: boolean) => { if (isFeatured) return FastImage.priority.high if (isVisible) return FastImage.priority.normal return FastImage.priority.low } ``` -------------------------------- ### Accessing FastImage Constants and Methods Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/types.md Demonstrates how to access static constants like resizeMode, priority, and cacheControl, as well as how to call methods such as preload, clearMemoryCache, and clearDiskCache. Ensure FastImage is imported. ```typescript import FastImage from 'react-native-fast-image' // Access constants FastImage.resizeMode.cover FastImage.priority.high FastImage.cacheControl.web // Call methods FastImage.preload([{ uri: '...' }]) await FastImage.clearMemoryCache() await FastImage.clearDiskCache() ``` -------------------------------- ### Clear Cache on Screen Navigation Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/static-methods.md This example demonstrates how to clear the memory cache when a screen is unfocused or navigated away from, using `useFocusEffect` from `@react-navigation/native`. ```typescript import React, { useEffect } from 'react' import { useFocusEffect } from '@react-navigation/native' import FastImage from 'react-native-fast-image' export default function GalleryScreen() { useFocusEffect( React.useCallback(() => { return () => { // Clear memory cache when leaving the screen FastImage.clearMemoryCache() } }, []) ) return null } ``` -------------------------------- ### FastImage Static Methods: Preload Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/architecture.md Demonstrates the `preload` static method, which is used to prefetch image sources by calling into native modules, optimizing subsequent image loading. ```typescript FastImage.preload(sources) → NativeModules.FastImageView.preload(sources) → iOS: SDWebImagePrefetcher.prefetchURLs() → Android: Glide.load() for each source ``` -------------------------------- ### Android Native Bridge Event Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/native-modules.md Send events from the native Android module to JavaScript using RCTEventEmitter. This example shows how to send progress events. ```java // Send events via RCTEventEmitter RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class) eventEmitter.receiveEvent(viewId, eventName, eventData) ``` ```java // Example: Send onFastImageProgress WritableMap event = new WritableNativeMap() event.putInt("loaded", (int) bytesRead) event.putInt("total", (int) expectedLength) eventEmitter.receiveEvent(viewId, "onFastImageProgress", event) ``` -------------------------------- ### SDWebImage Options Mapping for FastImage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/native-modules.md Illustrates how FastImage's priority and cache control enums map to SDWebImage's options. This mapping is handled by the RCTConvert+FFFastImage category. ```objc FFFPriorityLow → SDWebImageLowPriority FFFPriorityNormal → (default options) FFFPriorityHigh → SDWebImageHighPriority FFFCacheControlImmutable → (no additional options) FFFCacheControlWeb → SDWebImageRefreshCached FFFCacheControlCacheOnly → SDWebImageFromCacheOnly ``` -------------------------------- ### Basic Image Usage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/README.md Demonstrates how to use the FastImage component to display a remote image with custom headers and priority. This is the primary way to load images. ```jsx import FastImage from 'react-native-fast-image' const YourImage = () => ( ) ``` -------------------------------- ### Get Resize Mode Dynamically Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Selects the appropriate FastImage resize mode based on a type ('thumbnail' or 'full'). Use this to dynamically set the resizeMode prop. ```typescript const getResizeMode = (type: 'thumbnail' | 'full') => { const modes = { thumbnail: FastImage.resizeMode.cover, full: FastImage.resizeMode.contain } return modes[type] } ``` -------------------------------- ### Configure Cache Management with FastImage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/configuration.md Control cache behavior using static methods. Use `preload` to load images before display, `clearMemoryCache` for immediate cache removal, and `clearDiskCache` for a thorough cleanup. ```typescript FastImage.preload([ { uri: 'https://example.com/image1.jpg' }, { uri: 'https://example.com/image2.jpg' } ]) ``` ```typescript await FastImage.clearMemoryCache() ``` ```typescript await FastImage.clearDiskCache() ``` -------------------------------- ### Basic Image Loading Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/README.md Load an image from a URI with specified dimensions and resize mode. Ensure FastImage is imported. ```typescript import FastImage from 'react-native-fast-image' ``` -------------------------------- ### Get Cache Strategy Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Selects the FastImage cache control strategy based on content type ('static', 'dynamic', or 'offline'). Use this to manage image caching behavior. ```typescript const getCacheStrategy = (contentType: 'static' | 'dynamic' | 'offline') => { const strategies = { static: FastImage.cacheControl.immutable, dynamic: FastImage.cacheControl.web, offline: FastImage.cacheControl.cacheOnly } return strategies[contentType] } ``` -------------------------------- ### Cache Lookup Flow Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/architecture.md Illustrates the process of looking up an image, prioritizing memory cache, then disk cache, before resorting to a network fetch. ```text 1. Image URI requested │ ├─ Memory Cache Hit? │ └─ Load from memory (instant) │ └─ Skip onProgress, go to onLoad │ ├─ Disk Cache Hit? (if cache mode permits) │ └─ Load from disk │ └─ Minimal/no onProgress │ └─ Network Fetch └─ Download from server └─ Multiple onProgress callbacks └─ Cache to memory and disk └─ onLoad with dimensions ``` -------------------------------- ### Reinstall Dependencies Source: https://github.com/dylanvann/react-native-fast-image/blob/main/docs/troubleshooting.md Remove node_modules and reinstall dependencies. ```bash rm -rf node_modules && yarn ``` -------------------------------- ### iOS Native Bridge Events Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/native-modules.md Send events from the native iOS module to JavaScript using the RCTEventEmitter. Used for load start, progress, load completion, and error events. ```objective-c // Send onFastImageLoadStart event self.onFastImageLoadStart(@{}) ``` ```objective-c // Send onFastImageProgress event self.onFastImageProgress(@{ @"loaded": @(receivedSize), @"total": @(expectedSize) }) ``` ```objective-c // Send onFastImageLoad event with dimensions self.onFastImageLoad(@{ @"width": @(image.size.width), @"height": @(image.size.height) }) ``` ```objective-c // Send onFastImageError event self.onFastImageError(@{}) ``` ```objective-c // Send onFastImageLoadEnd event self.onFastImageLoadEnd(@{}) ``` -------------------------------- ### iOS Loading Flow Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/architecture.md Details the steps involved when an image is loaded on iOS, including prop updates, image reloading, and SDWebImage integration. ```text 1. Component Mounts └─ source prop set └─ Native layer receives prop update 2. iOS: FFFastImageView.reloadImage() └─ Parse source (URI, headers, priority, cache) └─ Set SDWebImageOptions based on priority/cache └─ Call sd_setImageWithURL with options └─ SDWebImage downloads and caches ``` -------------------------------- ### Memory-Efficient Gallery with Preloading Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/usage-patterns.md Implement a memory-efficient gallery by preloading images that become visible and managing those that are no longer visible. This pattern uses FlatList and FastImage's preload functionality. ```typescript import { FlatList } from 'react-native' import FastImage from 'react-native-fast-image' export function EfficientGallery({ images }: { images: Array<{ id: string; uri: string }> }) { const handleViewableItemsChanged = (info: any) => { const visible = info.viewableItems.map((item: any) => item.item) const notVisible = info.changed .filter((item: any) => !item.isViewable) .map((item: any) => item.item) // Preload visible images if (visible.length > 0) { FastImage.preload(visible.map(img => ({ uri: img.uri }))) } // Could implement memory cleanup for not visible // (Currently managed by native libraries) } return ( item.id} renderItem={({ item }) => ( )} onViewableItemsChanged={handleViewableItemsChanged} viewabilityConfig={{ itemVisiblePercentThreshold: 50 }} /> ) } ``` -------------------------------- ### Cache Only Mode Example Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/constants.md Utilize the 'cacheOnly' mode to load an image exclusively from the cache, making no network requests. This is suitable for offline support or when ensuring an image is already locally available. ```typescript // Offline fallback - use cached image if available { // Image not in cache, hide it setShowImage(false) }} /> ``` -------------------------------- ### Display Download Progress for Large Images Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/usage-patterns.md Use the `onProgress` prop to track download progress and display a progress bar and percentage. This is useful for large images where the download time might be noticeable. ```typescript import { useState } from 'react' import { View, Text, ProgressViewIOS } from 'react-native' import FastImage from 'react-native-fast-image' export function ImageWithProgress() { const [progress, setProgress] = useState(0) const handleProgress = (event: any) => { const percent = event.nativeEvent.loaded / event.nativeEvent.total setProgress(percent) } return ( {progress > 0 && progress < 1 && ( <> {Math.round(progress * 100)}% )} ) } ``` -------------------------------- ### Static Methods Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/architecture.md FastImage provides static methods for cache management and preloading images. ```APIDOC ## Static Methods ### `FastImage.preload(sources)` - **Description**: Preloads an array of image sources into the cache. - **Parameters**: - `sources` (Array): An array of image source objects to preload. - **Native Implementation**: - `NativeModules.FastImageView.preload(sources)` - iOS: `SDWebImagePrefetcher.prefetchURLs()` - Android: `Glide.load()` for each source ### `FastImage.clearMemoryCache()` - **Description**: Clears the memory cache. - **Returns**: `Promise` - **Native Implementation**: - `NativeModules.FastImageView.clearMemoryCache()` - iOS: `SDImageCache.clearMemory()` - Android: `Glide.clearMemory()` ### `FastImage.clearDiskCache()` - **Description**: Clears the disk cache. - **Returns**: `Promise` - **Native Implementation**: - `NativeModules.FastImageView.clearDiskCache()` - iOS: `SDImageCache.clearDiskOnCompletion()` - Android: `Glide.clearDiskCache()` ``` -------------------------------- ### Handle Image Load Errors Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/events-and-callbacks.md Use the onError callback to set an error state and display a message when an image fails to load. This example shows how to conditionally render text based on the error state. ```typescript const [hasError, setHasError] = useState(false) { setHasError(true) console.error(`Failed to load image: ${imageUrl}`) }} /> {hasError && Image failed to load} ``` -------------------------------- ### Clear Cache When Memory is Low Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/static-methods.md This example shows how to clear the memory cache when the application state changes, specifically when it moves to the background and then becomes active again. It utilizes `AppState` from `react-native` to monitor application state changes. ```typescript import { AppState } from 'react-native' import FastImage from 'react-native-fast-image' let appState = useRef(AppState.currentState) useEffect(() => { const subscription = AppState.addEventListener('change', handleAppStateChange) return () => subscription.remove() }, []) const handleAppStateChange = async (nextAppState) => { // Clear cache if app moves to background if (appState.current.match(/inactive|background/) && nextAppState === 'active') { await FastImage.clearMemoryCache() } appState.current = nextAppState } ``` -------------------------------- ### Implement Retry Logic on Error Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/events-and-callbacks.md Implement retry logic within the onError callback to attempt reloading the image a limited number of times. This example clears memory cache and increments a retry count before forcing a re-render. ```typescript const [retryCount, setRetryCount] = useState(0) const MAX_RETRIES = 3 const handleError = () => { if (retryCount < MAX_RETRIES) { // Clear cache and retry FastImage.clearMemoryCache().then(() => { setRetryCount(retryCount + 1) setKey(key + 1) // Force re-render }) } } ``` -------------------------------- ### Display Image with Placeholder Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/usage-patterns.md Show a placeholder image until the actual image from the URI is loaded. This improves perceived performance by providing immediate visual feedback. ```typescript import { useState } from 'react' import { Image, View } from 'react-native' import FastImage from 'react-native-fast-image' export function ImageWithPlaceholder({ uri }: { uri: string }) { const [imageLoaded, setImageLoaded] = useState(false) return ( {!imageLoaded && ( )} setImageLoaded(true)} /> ) } ``` -------------------------------- ### Maintain Aspect Ratio with Responsive Image Container Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/usage-patterns.md Use the `onLoad` prop to get image dimensions and dynamically set the aspect ratio of the container. This ensures the image scales correctly and maintains its original proportions within a responsive layout. ```typescript import { useState } from 'react' import { View, Dimensions } from 'react-native' import FastImage from 'react-native-fast-image' export function ResponsiveImage({ uri }: { uri: string }) { const [aspectRatio, setAspectRatio] = useState(16 / 9) const containerWidth = Dimensions.get('window').width return ( { const { width, height } = event.nativeEvent setAspectRatio(width / height) }} /> ) } ``` -------------------------------- ### FastImage Static Methods Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/README.md Provides static methods for managing image preloading and cache operations. ```APIDOC ## FastImage Static Methods ### Description This section details the static methods available on the `FastImage` module for advanced image management. ### `preload` #### Description Preloads an array of images into the cache. #### Parameters - `sources` (Array<`Source`>): An array of image source objects to preload. #### Example ```typescript FastImage.preload([ { uri: 'https://example.com/image1.jpg' }, { uri: 'https://example.com/image2.jpg' } ]) ``` ### `clearMemoryCache` #### Description Clears all images from the memory cache. #### Example ```typescript await FastImage.clearMemoryCache() ``` ### `clearDiskCache` #### Description Clears all images from the disk cache. #### Example ```typescript await FastImage.clearDiskCache() ``` ``` -------------------------------- ### Preload Images with FastImage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/README.md Use `FastImage.preload` to load images into the cache before they are displayed. This can improve performance by ensuring images are ready when needed. It accepts an array of source objects, each with a `uri` and optional `headers`. ```javascript FastImage.preload([ { uri: 'https://facebook.github.io/react/img/logo_og.png', headers: { Authorization: 'someAuthToken' }, }, { uri: 'https://facebook.github.io/react/img/logo_og.png', headers: { Authorization: 'someAuthToken' }, }, ]) ``` -------------------------------- ### Image Caching Strategies with FastImage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/usage-patterns.md Utilize different caching strategies like immutable, web, and cacheOnly for various content types. Ensure FastImage is imported. ```typescript import FastImage from 'react-native-fast-image' export function CachedImages() { return ( <> {/* Static asset - immutable cache */} {/* Dynamic content - respect server headers */} {/* Offline fallback - cache only */} console.log('Image not in cache')} /> ) } ``` -------------------------------- ### Reinstall Pods Source: https://github.com/dylanvann/react-native-fast-image/blob/main/docs/troubleshooting.md Reinstall CocoaPods dependencies. ```bash cd ios && pod install ``` -------------------------------- ### Android Loading Flow Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/architecture.md Details the steps involved when an image is loaded on Android, including prop updates, native view updates, and Glide integration. ```text 3. Android: FastImageViewWithUrl.onAfterUpdate() └─ Parse source with FastImageViewConverter └─ Build Glide RequestOptions └─ Glide.load() with options └─ Glide downloads and caches ``` -------------------------------- ### FastImage.preload() Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/api-reference/static-methods.md Preloads one or more images into the device cache. This method queues images for download with normal priority and caches them according to their settings. The operation is asynchronous, returning immediately while the download occurs in the background. ```APIDOC ## FastImage.preload() ### Description Preloads one or more images into the device cache. This method queues the images to be downloaded with normal priority (unless specified otherwise in the source config). Preloaded images will be cached according to their cache control settings. This operation is asynchronous—the function returns immediately, but actual download happens in the background. ### Method Signature ```typescript FastImage.preload(sources: Source[]) => void ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **sources** (`Source[]`) - Required - Array of image sources to preload. Each source object can include `uri`, `headers`, `priority`, and `cache`. ### Request Example ```javascript import FastImage from 'react-native-fast-image' // Basic preload FastImage.preload([ { uri: 'https://example.com/image1.jpg' }, { uri: 'https://example.com/image2.jpg' }, { uri: 'https://example.com/image3.jpg' } ]) // Preload with authentication headers const authToken = 'eyJhbGci...' FastImage.preload([ { uri: 'https://api.example.com/user/avatar.jpg', headers: { Authorization: `Bearer ${authToken}` } }, { uri: 'https://api.example.com/banner.jpg', headers: { Authorization: `Bearer ${authToken}` } } ]) // Preload with priority and cache settings FastImage.preload([ { uri: 'https://example.com/hero-image.jpg', priority: FastImage.priority.high, cache: FastImage.cacheControl.web }, { uri: 'https://example.com/thumbnail.jpg', priority: FastImage.priority.normal, cache: FastImage.cacheControl.immutable } ]) ``` ### Response #### Success Response (void) This method is synchronous and does not return a value. The preloading operation happens in the background. #### Response Example N/A (void return type) ``` -------------------------------- ### Preloading Images in a FlatList with FastImage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/usage-patterns.md Preload the next page of images as a user scrolls to improve perceived performance in infinite lists. Requires FlatList and FastImage imports. ```typescript import { FlatList } from 'react-native' import FastImage from 'react-native-fast-image' const PAGE_SIZE = 10 interface Item { id: string imageUri: string title: string } export function InfiniteImageList({ items }: { items: Item[] }) { const handleEndReached = () => { // Preload next page const nextPageStart = items.length const nextPageItems = items.slice(nextPageStart, nextPageStart + PAGE_SIZE) FastImage.preload( nextPageItems.map(item => ({ uri: item.imageUri })) ) } return ( item.id} renderItem={({ item }) => ( )} onEndReached={handleEndReached} onEndReachedThreshold={0.5} /> ) } ``` -------------------------------- ### iOS Header Implementation with SDWebImage Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/architecture.md Configures SDWebImage to include custom headers in download requests on iOS. ```objc SDWebImageDownloaderRequestModifier requestModifierWithBlock: ^NSURLRequest* (NSURLRequest* request) { NSMutableURLRequest* mutableRequest = [request mutableCopy]; for (NSString* header in headers) { [mutableRequest setValue:headers[header] forHTTPHeaderField:header]; } return [mutableRequest copy]; } ``` -------------------------------- ### FastImage Static Methods: Clear Disk Cache Source: https://github.com/dylanvann/react-native-fast-image/blob/main/_autodocs/architecture.md Illustrates the `clearDiskCache` static method, which clears the disk cache for images by interacting with native modules on iOS and Android. ```typescript FastImage.clearDiskCache() → NativeModules.FastImageView.clearDiskCache() → iOS: SDImageCache.clearDiskOnCompletion() → Android: Glide.clearDiskCache() ```