Answer the question
In order to leave comments, you need to log in
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));
}, []);
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);
};
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question