Skip to content

Instantly share code, notes, and snippets.

@borispoehland
Created February 18, 2021 14:11
Show Gist options
  • Save borispoehland/b1dc73fc50b8e04610a9627a56b919c2 to your computer and use it in GitHub Desktop.
Save borispoehland/b1dc73fc50b8e04610a9627a56b919c2 to your computer and use it in GitHub Desktop.
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