Created
February 18, 2021 14:11
-
-
Save borispoehland/b1dc73fc50b8e04610a9627a56b919c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from 'react'; | |
interface IProps { | |
imagesToLoad: string[], | |
} | |
const useImagesAreLoaded = ({ imagesToLoad }: IProps): boolean => { | |
const [loadedTilesCount, setLoadedTilesCount] = useState(0); | |
useEffect((): void => { | |
imagesToLoad.forEach((src: string): void => { | |
const img = new Image(); | |
img.src = src; // by setting an src, you trigger browser download | |
img.onload = (): void => { | |
// when it finishes loading, update the component state | |
setLoadedTilesCount((prevCount: number): number => prevCount + 1); | |
}; | |
}); | |
}, []); | |
return loadedTilesCount === imagesToLoad.length; | |
}; | |
export default useImagesAreLoaded; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment