Skip to content

Instantly share code, notes, and snippets.

@tera-ny
Last active November 13, 2022 16:13
Show Gist options
  • Save tera-ny/538378df6fe91e1652932ce7ba5d3290 to your computer and use it in GitHub Desktop.
Save tera-ny/538378df6fe91e1652932ce7ba5d3290 to your computer and use it in GitHub Desktop.
Component to preload images
import { FC, PropsWithChildren, ReactNode, useEffect, useState } from "react";
interface Props {
srcSets: { [key: string]: string };
fallback?: ReactNode;
}
const Preload: FC<PropsWithChildren<Props>> = ({
children,
fallback,
srcSets,
}) => {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
Promise.all(
Object.values(srcSets).map(
(src) =>
new Promise<void>((resolve) => {
const img = new Image();
img.onload = () => {
resolve();
};
img.src = src;
})
)
).then(() => {
setIsLoaded(true);
});
}, [srcSets]);
if (isLoaded) {
return <>{children}</>;
} else {
return <>{fallback}</>;
}
};
export default Preload;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment