Categories
React Answers

How to preload images with React and JavaScript?

Spread the love

Sometimes, we want to preload images with React and JavaScript.

In this article, we’ll look at how to preload images with React and JavaScript.

How to preload images with React and JavaScript?

To preload images with React and JavaScript, we can create our own hook.

import { useEffect } from "react";

export const usePreloadImages = (imageSrcs) => {
  useEffect(() => {
    const randomStr = Math.random().toString(32).slice(2) + Date.now();
    window.usePreloadImagesData = window.usePreloadImagesData ?? {};
    window.usePreloadImagesData[randomStr] = [];
    for (const src of imageSrcs) {
      const img = new Image();
      img.src = src;
      window.usePreloadImagesData[randomStr].push(img);
    }
    return () => {
      delete window.usePreloadImagesData?.[randomStr];
    };
  }, [imageSrcs]);
};

We add the useEffect hook to store the images in the window.usePreloadImagesData property array.

The we create Image instances and push them to the array.

Once, the component unmounts, we clear window.usePreloadImagesData with

delete window.usePreloadImagesData?.[randomStr];

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *