diff --git a/src/components/ThumbnailImage.tsx b/src/components/ThumbnailImage.tsx index 5c5932c5814b..029f12834f89 100644 --- a/src/components/ThumbnailImage.tsx +++ b/src/components/ThumbnailImage.tsx @@ -11,6 +11,11 @@ import Icon from './Icon'; import * as Expensicons from './Icon/Expensicons'; import ImageWithSizeCalculation from './ImageWithSizeCalculation'; +// Cache for the dimensions of the thumbnails to avoid flickering incorrect size when the +// image has already been loaded once. This caches the dimensions based on the URL of +// the image. +const thumbnailDimensionsCache = new Map(); + type ThumbnailImageProps = { /** Source URL for the preview image */ previewSourceURL: string | ImageSourcePropType; @@ -56,7 +61,8 @@ function ThumbnailImage({ const theme = useTheme(); const {isOffline} = useNetwork(); const [failedToLoad, setFailedToLoad] = useState(false); - const [imageDimensions, setImageDimensions] = useState({width: imageWidth, height: imageHeight}); + const cachedDimensions = shouldDynamicallyResize && typeof previewSourceURL === 'string' ? thumbnailDimensionsCache.get(previewSourceURL) : null; + const [imageDimensions, setImageDimensions] = useState({width: cachedDimensions?.width ?? imageWidth, height: cachedDimensions?.height ?? imageHeight}); const {thumbnailDimensionsStyles} = useThumbnailDimensions(imageDimensions.width, imageDimensions.height); useEffect(() => { @@ -69,12 +75,21 @@ function ThumbnailImage({ */ const updateImageSize = useCallback( ({width, height}: UpdateImageSizeParams) => { - if (!shouldDynamicallyResize) { + if ( + !shouldDynamicallyResize || + // If the provided dimensions are good avoid caching them and updating state. + (imageDimensions.width === width && imageDimensions.height === height) + ) { return; } + + if (typeof previewSourceURL === 'string') { + thumbnailDimensionsCache.set(previewSourceURL, {width, height}); + } + setImageDimensions({width, height}); }, - [shouldDynamicallyResize], + [previewSourceURL, imageDimensions, shouldDynamicallyResize], ); const sizeStyles = shouldDynamicallyResize ? [thumbnailDimensionsStyles] : [styles.w100, styles.h100];