I sat for a long time solving the problem of pre-loading pictures. What’s the problem? I have a page with a loader. I need to be redirected to the main page when all the pictures of the main page are loaded.
I found an interesting solution in the internet with the hook usePreloadImages here is its code:
import { useEffect, useState } from 'react'
function preloadImage(src: string) {
return new Promise((resolve, reject) => {
const img = new Image()
img.src = src
img.onload = function () {
resolve(img)
}
img.onerror = img.onabort = function () {
reject(src)
}
})
}
export default function useImagePreloader(imageList: string[]) {
const [imagesPreloaded, setImagesPreloaded] = useState<boolean>(false)
useEffect(() => {
let isCancelled = false
async function effect() {
if (isCancelled) {
return
}
const imagesPromiseList: Promise<any>[] = []
for (const i of imageList) {
imagesPromiseList.push(preloadImage(i))
}
await Promise.all(imagesPromiseList)
if (isCancelled) {
return
}
setImagesPreloaded(true)
}
effect()
return () => {
isCancelled = true
}
}, [imageList])
return { imagesPreloaded }
}
This solution seems to work, but when loading all the pictures I am redirected to the main page and the pictures are re-loaded. The images to be loaded are in the public folder if it matters