How to prefetch SVG Icons / Images in react native

date
Jul 28, 2023
slug
prefetch-svg-or-images-rn
status
Published
tags
React Native
Performance
summary
type
Post
— This works only for iOS as of now, I’m looking for a way to do it in Android as well —
This react hook utilises the prefetch method of the native Image component to proactively cache the necessary icons and images.
In the event of encountering an SVG image, an error may occur; however, it can be disregarded as the prefetched URL remains usable with the react-native-svg library to effectively incorporate the cached icon.
import {useEffect} from 'react';
import {Image} from 'react-native';

const usePrefetchedImages = imageUrls => {
  useEffect(() => {
    const prefetchImages = async () => {
      const tasks = imageUrls.map(async url => {
        try {
          await Image.prefetch(url);
        } catch (error) {
          if (!url.includes('.svg')) {
            console.warn(`Image prefetch failed at URL: ${url}`, error);
          }
        }
      });
      await Promise.all(tasks);
    };

    prefetchImages();
  }, [imageUrls]);
};

export default usePrefetchImages;
Usage example
import React from "react";
import { View } from "react-native";
import { SvgUri } from "react-native-svg";

import { usePrefetchedImages } from "@/hooks";

const SVGTest = () => {
  const CROSS_ICON = "https://example.com/icons/2x/cross.svg";
  usePrefetchedImages([CROSS_ICON]);

  return (
    <View>
      <SvgUri url={CROSS_ICON} />
    </View>
  );
};

export default SVGTest;

© Nikit Singh 2020 - 2024