U
U
uRoot2021-01-26 13:55:43
React
uRoot, 2021-01-26 13:55:43

How to wait for all images to load in React?

There are a lot of small pictures, they are about 6k, but they are all a couple of Kb. Links to these pictures are stored in an array. How do I wait for all these pictures to load in React?

I try like this:

App.js

useEffect(() => {
    cacheImages()
      .catch(console.log)
      .finally(() =>isLoading(false));
  }, []);

Cam cacheImages:
const cacheImages = async () => {
  const promises = await srcArray.map(src => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = resolve;
      img.onerror = reject;
      img.src = src;
      window[src] = img;
    });
  });

  await Promise.all(promises);
};

But in the end, the project cannot be fully loaded and just freezes. Any ideas or how to fix this, or how to just wait for the images to load?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew Hecc, 2021-01-26
@Hecc

Making 6k requests from the client to download something is not ok. Here the most basic problem is the number of requests.
Maybe it makes sense to collect all the pictures in some kind of sprite with the same webpack?
If you don’t want all 6k in one sprite, you can come up with some kind of logic, collect it somehow by components or simply by quantity, conditionally in 1 sprite of 500 pictures.
The number of requests will then be reduced to the number of sprites and there will definitely not be such a problem with loading.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question