useImg is a react hook that allows you to load images with a loading state and error state, and also allows you to render the image safely when it is loaded and decoded.
npm install @nouraldeen/use-img
import React from "react";
import useImg from "@nouraldeen/use-img";
const ImageWrapper = () => {
const { status, image, error } = useImg("https://example.com/image.jpg");
if (status === "loading") {
return <p>Loading...</p>;
}
if (status === "error") {
return <p>Error: {error.message}</p>;
}
if (status === "loaded") {
return <img src="placeholder.png" alt="image" />;
}
return <img src={image.src} alt="image" />;
};
export default ImageWrapper;
useImg(src: string): { status: 'loading' | 'error' | 'loaded' | "ready", image: HTMLImageElement | null, error: Error | null }
by using status.ready you can know when the image is loaded and decoded and ready to be rendered safely without any flickering.
example:
status.ready && <img src={image.src} alt="image" />;
other status values are:
- status.loading: when the image is still loading.
- status.error: when the image failed to load.
- status.loaded: when the image is loaded but not decoded yet.
This project is licensed under the MIT License.